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,475 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { createRequire as __cometCreateRequire } from 'module';
|
|
3
|
+
const require = __cometCreateRequire(import.meta.url);
|
|
4
|
+
var TL=Object.create;var dw=Object.defineProperty;var OL=Object.getOwnPropertyDescriptor;var jL=Object.getOwnPropertyNames;var $L=Object.getPrototypeOf,DL=Object.prototype.hasOwnProperty;var Xf=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(t,r)=>(typeof require<"u"?require:t)[r]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')});var x=(e,t,r)=>()=>{if(r)throw r[0];try{return e&&(t=e(e=0)),t}catch(n){throw r=[n],n}};var $=(e,t)=>()=>{try{return t||e((t={exports:{}}).exports,t),t.exports}catch(r){throw t=0,r}},fw=(e,t)=>{for(var r in t)dw(e,r,{get:t[r],enumerable:!0})},BL=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of jL(t))!DL.call(e,i)&&i!==r&&dw(e,i,{get:()=>t[i],enumerable:!(n=OL(t,i))||n.enumerable});return e};var dr=(e,t,r)=>(r=e!=null?TL($L(e)):{},BL(t||!e||!e.__esModule?dw(r,"default",{value:e,enumerable:!0}):r,e));var De=$(nr=>{"use strict";var pw=Symbol.for("yaml.alias"),IE=Symbol.for("yaml.document"),Zf=Symbol.for("yaml.map"),xE=Symbol.for("yaml.pair"),mw=Symbol.for("yaml.scalar"),ep=Symbol.for("yaml.seq"),Xi=Symbol.for("yaml.node.type"),WL=e=>!!e&&typeof e=="object"&&e[Xi]===pw,qL=e=>!!e&&typeof e=="object"&&e[Xi]===IE,LL=e=>!!e&&typeof e=="object"&&e[Xi]===Zf,VL=e=>!!e&&typeof e=="object"&&e[Xi]===xE,PE=e=>!!e&&typeof e=="object"&&e[Xi]===mw,ML=e=>!!e&&typeof e=="object"&&e[Xi]===ep;function TE(e){if(e&&typeof e=="object")switch(e[Xi]){case Zf:case ep:return!0}return!1}function FL(e){if(e&&typeof e=="object")switch(e[Xi]){case pw:case Zf:case mw:case ep:return!0}return!1}var HL=e=>(PE(e)||TE(e))&&!!e.anchor;nr.ALIAS=pw;nr.DOC=IE;nr.MAP=Zf;nr.NODE_TYPE=Xi;nr.PAIR=xE;nr.SCALAR=mw;nr.SEQ=ep;nr.hasAnchor=HL;nr.isAlias=WL;nr.isCollection=TE;nr.isDocument=qL;nr.isMap=LL;nr.isNode=FL;nr.isPair=VL;nr.isScalar=PE;nr.isSeq=ML});var Ul=$(hw=>{"use strict";var Qt=De(),Hr=Symbol("break visit"),OE=Symbol("skip children"),bi=Symbol("remove node");function tp(e,t){let r=jE(t);Qt.isDocument(e)?tc(null,e.contents,r,Object.freeze([e]))===bi&&(e.contents=null):tc(null,e,r,Object.freeze([]))}tp.BREAK=Hr;tp.SKIP=OE;tp.REMOVE=bi;function tc(e,t,r,n){let i=$E(e,t,r,n);if(Qt.isNode(i)||Qt.isPair(i))return DE(e,n,i),tc(e,i,r,n);if(typeof i!="symbol"){if(Qt.isCollection(t)){n=Object.freeze(n.concat(t));for(let o=0;o<t.items.length;++o){let a=tc(o,t.items[o],r,n);if(typeof a=="number")o=a-1;else{if(a===Hr)return Hr;a===bi&&(t.items.splice(o,1),o-=1)}}}else if(Qt.isPair(t)){n=Object.freeze(n.concat(t));let o=tc("key",t.key,r,n);if(o===Hr)return Hr;o===bi&&(t.key=null);let a=tc("value",t.value,r,n);if(a===Hr)return Hr;a===bi&&(t.value=null)}}return i}async function rp(e,t){let r=jE(t);Qt.isDocument(e)?await rc(null,e.contents,r,Object.freeze([e]))===bi&&(e.contents=null):await rc(null,e,r,Object.freeze([]))}rp.BREAK=Hr;rp.SKIP=OE;rp.REMOVE=bi;async function rc(e,t,r,n){let i=await $E(e,t,r,n);if(Qt.isNode(i)||Qt.isPair(i))return DE(e,n,i),rc(e,i,r,n);if(typeof i!="symbol"){if(Qt.isCollection(t)){n=Object.freeze(n.concat(t));for(let o=0;o<t.items.length;++o){let a=await rc(o,t.items[o],r,n);if(typeof a=="number")o=a-1;else{if(a===Hr)return Hr;a===bi&&(t.items.splice(o,1),o-=1)}}}else if(Qt.isPair(t)){n=Object.freeze(n.concat(t));let o=await rc("key",t.key,r,n);if(o===Hr)return Hr;o===bi&&(t.key=null);let a=await rc("value",t.value,r,n);if(a===Hr)return Hr;a===bi&&(t.value=null)}}return i}function jE(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 $E(e,t,r,n){if(typeof r=="function")return r(e,t,n);if(Qt.isMap(t))return r.Map?.(e,t,n);if(Qt.isSeq(t))return r.Seq?.(e,t,n);if(Qt.isPair(t))return r.Pair?.(e,t,n);if(Qt.isScalar(t))return r.Scalar?.(e,t,n);if(Qt.isAlias(t))return r.Alias?.(e,t,n)}function DE(e,t,r){let n=t[t.length-1];if(Qt.isCollection(n))n.items[e]=r;else if(Qt.isPair(n))e==="key"?n.key=r:n.value=r;else if(Qt.isDocument(n))n.contents=r;else{let i=Qt.isAlias(n)?"alias":"scalar";throw new Error(`Cannot replace node with ${i} parent`)}}hw.visit=tp;hw.visitAsync=rp});var gw=$(WE=>{"use strict";var BE=De(),QL=Ul(),UL={"!":"%21",",":"%2C","[":"%5B","]":"%5D","{":"%7B","}":"%7D"},JL=e=>e.replace(/[!,[\]{}]/g,t=>UL[t]),Jl=class e{constructor(t,r){this.docStart=null,this.docEnd=!1,this.yaml=Object.assign({},e.defaultYaml,t),this.tags=Object.assign({},e.defaultTags,r)}clone(){let t=new e(this.yaml,this.tags);return t.docStart=this.docStart,t}atDocument(){let t=new e(this.yaml,this.tags);switch(this.yaml.version){case"1.1":this.atNextDocument=!0;break;case"1.2":this.atNextDocument=!1,this.yaml={explicit:e.defaultYaml.explicit,version:"1.2"},this.tags=Object.assign({},e.defaultTags);break}return t}add(t,r){this.atNextDocument&&(this.yaml={explicit:e.defaultYaml.explicit,version:"1.1"},this.tags=Object.assign({},e.defaultTags),this.atNextDocument=!1);let n=t.trim().split(/[ \t]+/),i=n.shift();switch(i){case"%TAG":{if(n.length!==2&&(r(0,"%TAG directive should contain exactly two parts"),n.length<2))return!1;let[o,a]=n;return this.tags[o]=a,!0}case"%YAML":{if(this.yaml.explicit=!0,n.length!==1)return r(0,"%YAML directive should contain exactly one part"),!1;let[o]=n;if(o==="1.1"||o==="1.2")return this.yaml.version=o,!0;{let a=/^\d+\.\d+$/.test(o);return r(6,`Unsupported YAML version ${o}`,a),!1}}default:return r(0,`Unknown directive ${i}`,!0),!1}}tagName(t,r){if(t==="!")return"!";if(t[0]!=="!")return r(`Not a valid tag: ${t}`),null;if(t[1]==="<"){let a=t.slice(2,-1);return a==="!"||a==="!!"?(r(`Verbatim tags aren't resolved, so ${t} is invalid.`),null):(t[t.length-1]!==">"&&r("Verbatim tags must end with a >"),a)}let[,n,i]=t.match(/^(.*!)([^!]*)$/s);i||r(`The ${t} tag has no suffix`);let o=this.tags[n];if(o)try{return o+decodeURIComponent(i)}catch(a){return r(String(a)),null}return n==="!"?t:(r(`Could not resolve tag: ${t}`),null)}tagString(t){for(let[r,n]of Object.entries(this.tags))if(t.startsWith(n))return r+JL(t.substring(n.length));return t[0]==="!"?t:`!<${t}>`}toString(t){let r=this.yaml.explicit?[`%YAML ${this.yaml.version||"1.2"}`]:[],n=Object.entries(this.tags),i;if(t&&n.length>0&&BE.isNode(t.contents)){let o={};QL.visit(t.contents,(a,s)=>{BE.isNode(s)&&s.tag&&(o[s.tag]=!0)}),i=Object.keys(o)}else i=[];for(let[o,a]of n)o==="!!"&&a==="tag:yaml.org,2002:"||(!t||i.some(s=>s.startsWith(a)))&&r.push(`%TAG ${o} ${a}`);return r.join(`
|
|
5
|
+
`)}};Jl.defaultYaml={explicit:!1,version:"1.2"};Jl.defaultTags={"!!":"tag:yaml.org,2002:"};WE.Directives=Jl});var np=$(zl=>{"use strict";var qE=De(),zL=Ul();function KL(e){if(/[\x00-\x19\s,[\]{}]/.test(e)){let r=`Anchor must not contain whitespace or control characters: ${JSON.stringify(e)}`;throw new Error(r)}return!0}function LE(e){let t=new Set;return zL.visit(e,{Value(r,n){n.anchor&&t.add(n.anchor)}}),t}function VE(e,t){for(let r=1;;++r){let n=`${e}${r}`;if(!t.has(n))return n}}function GL(e,t){let r=[],n=new Map,i=null;return{onAnchor:o=>{r.push(o),i??(i=LE(e));let a=VE(t,i);return i.add(a),a},setAnchors:()=>{for(let o of r){let a=n.get(o);if(typeof a=="object"&&a.anchor&&(qE.isScalar(a.node)||qE.isCollection(a.node)))a.node.anchor=a.anchor;else{let s=new Error("Failed to resolve repeated object (this should not happen)");throw s.source=o,s}}},sourceObjects:n}}zl.anchorIsValid=KL;zl.anchorNames=LE;zl.createNodeAnchors=GL;zl.findNewAnchor=VE});var vw=$(ME=>{"use strict";function Kl(e,t,r,n){if(n&&typeof n=="object")if(Array.isArray(n))for(let i=0,o=n.length;i<o;++i){let a=n[i],s=Kl(e,n,String(i),a);s===void 0?delete n[i]:s!==a&&(n[i]=s)}else if(n instanceof Map)for(let i of Array.from(n.keys())){let o=n.get(i),a=Kl(e,n,i,o);a===void 0?n.delete(i):a!==o&&n.set(i,a)}else if(n instanceof Set)for(let i of Array.from(n)){let o=Kl(e,n,i,i);o===void 0?n.delete(i):o!==i&&(n.delete(i),n.add(o))}else for(let[i,o]of Object.entries(n)){let a=Kl(e,n,i,o);a===void 0?delete n[i]:a!==o&&(n[i]=a)}return e.call(t,r,n)}ME.applyReviver=Kl});var Io=$(HE=>{"use strict";var YL=De();function FE(e,t,r){if(Array.isArray(e))return e.map((n,i)=>FE(n,String(i),r));if(e&&typeof e.toJSON=="function"){if(!r||!YL.hasAnchor(e))return e.toJSON(t,r);let n={aliasCount:0,count:1,res:void 0};r.anchors.set(e,n),r.onCreate=o=>{n.res=o,delete r.onCreate};let i=e.toJSON(t,r);return r.onCreate&&r.onCreate(i),i}return typeof e=="bigint"&&!r?.keep?Number(e):e}HE.toJS=FE});var ip=$(UE=>{"use strict";var XL=vw(),QE=De(),ZL=Io(),ww=class{constructor(t){Object.defineProperty(this,QE.NODE_TYPE,{value:t})}clone(){let t=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return this.range&&(t.range=this.range.slice()),t}toJS(t,{mapAsMap:r,maxAliasCount:n,onAnchor:i,reviver:o}={}){if(!QE.isDocument(t))throw new TypeError("A document argument is required");let a={anchors:new Map,doc:t,keep:!0,mapAsMap:r===!0,mapKeyWarned:!1,maxAliasCount:typeof n=="number"?n:100},s=ZL.toJS(this,"",a);if(typeof i=="function")for(let{count:c,res:l}of a.anchors.values())i(l,c);return typeof o=="function"?XL.applyReviver(o,{"":s},"",s):s}};UE.NodeBase=ww});var Gl=$(JE=>{"use strict";var eV=np(),tV=Ul(),nc=De(),rV=ip(),nV=Io(),yw=class extends rV.NodeBase{constructor(t){super(nc.ALIAS),this.source=t,Object.defineProperty(this,"tag",{set(){throw new Error("Alias nodes cannot have tags")}})}resolve(t,r){if(r?.maxAliasCount===0)throw new ReferenceError("Alias resolution is disabled");let n;r?.aliasResolveCache?n=r.aliasResolveCache:(n=[],tV.visit(t,{Node:(o,a)=>{(nc.isAlias(a)||nc.hasAnchor(a))&&n.push(a)}}),r&&(r.aliasResolveCache=n));let i;for(let o of n){if(o===this)break;o.anchor===this.source&&(i=o)}return i}toJSON(t,r){if(!r)return{source:this.source};let{anchors:n,doc:i,maxAliasCount:o}=r,a=this.resolve(i,r);if(!a){let c=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new ReferenceError(c)}let s=n.get(a);if(s||(nV.toJS(a,null,r),s=n.get(a)),s?.res===void 0){let c="This should not happen: Alias anchor was not resolved?";throw new ReferenceError(c)}if(o>=0&&(s.count+=1,s.aliasCount===0&&(s.aliasCount=op(i,a,n)),s.count*s.aliasCount>o)){let c="Excessive alias count indicates a resource exhaustion attack";throw new ReferenceError(c)}return s.res}toString(t,r,n){let i=`*${this.source}`;if(t){if(eV.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 op(e,t,r){if(nc.isAlias(t)){let n=t.resolve(e),i=r&&n&&r.get(n);return i?i.count*i.aliasCount:0}else if(nc.isCollection(t)){let n=0;for(let i of t.items){let o=op(e,i,r);o>n&&(n=o)}return n}else if(nc.isPair(t)){let n=op(e,t.key,r),i=op(e,t.value,r);return Math.max(n,i)}return 1}JE.Alias=yw});var jt=$(kw=>{"use strict";var iV=De(),oV=ip(),aV=Io(),sV=e=>!e||typeof e!="function"&&typeof e!="object",xo=class extends oV.NodeBase{constructor(t){super(iV.SCALAR),this.value=t}toJSON(t,r){return r?.keep?this.value:aV.toJS(this.value,t,r)}toString(){return String(this.value)}};xo.BLOCK_FOLDED="BLOCK_FOLDED";xo.BLOCK_LITERAL="BLOCK_LITERAL";xo.PLAIN="PLAIN";xo.QUOTE_DOUBLE="QUOTE_DOUBLE";xo.QUOTE_SINGLE="QUOTE_SINGLE";kw.Scalar=xo;kw.isScalarValue=sV});var Yl=$(KE=>{"use strict";var cV=Gl(),Oa=De(),zE=jt(),lV="tag:yaml.org,2002:";function uV(e,t,r){if(t){let n=r.filter(o=>o.tag===t),i=n.find(o=>!o.format)??n[0];if(!i)throw new Error(`Tag ${t} not found`);return i}return r.find(n=>n.identify?.(e)&&!n.format)}function dV(e,t,r){if(Oa.isDocument(e)&&(e=e.contents),Oa.isNode(e))return e;if(Oa.isPair(e)){let f=r.schema[Oa.MAP].createNode?.(r.schema,null,r);return f.items.push(e),f}(e instanceof String||e instanceof Number||e instanceof Boolean||typeof BigInt<"u"&&e instanceof BigInt)&&(e=e.valueOf());let{aliasDuplicateObjects:n,onAnchor:i,onTagObj:o,schema:a,sourceObjects:s}=r,c;if(n&&e&&typeof e=="object"){if(c=s.get(e),c)return c.anchor??(c.anchor=i(e)),new cV.Alias(c.anchor);c={anchor:null,node:null},s.set(e,c)}t?.startsWith("!!")&&(t=lV+t.slice(2));let l=uV(e,t,a.tags);if(!l){if(e&&typeof e.toJSON=="function"&&(e=e.toJSON()),!e||typeof e!="object"){let f=new zE.Scalar(e);return c&&(c.node=f),f}l=e instanceof Map?a[Oa.MAP]:Symbol.iterator in Object(e)?a[Oa.SEQ]:a[Oa.MAP]}o&&(o(l),delete r.onTagObj);let u=l?.createNode?l.createNode(r.schema,e,r):typeof l?.nodeClass?.from=="function"?l.nodeClass.from(r.schema,e,r):new zE.Scalar(e);return t?u.tag=t:l.default||(u.tag=l.tag),c&&(c.node=u),u}KE.createNode=dV});var sp=$(ap=>{"use strict";var fV=Yl(),Ai=De(),pV=ip();function bw(e,t,r){let n=r;for(let i=t.length-1;i>=0;--i){let o=t[i];if(typeof o=="number"&&Number.isInteger(o)&&o>=0){let a=[];a[o]=n,n=a}else n=new Map([[o,n]])}return fV.createNode(n,void 0,{aliasDuplicateObjects:!1,keepUndefined:!1,onAnchor:()=>{throw new Error("This should not happen, please report a bug.")},schema:e,sourceObjects:new Map})}var GE=e=>e==null||typeof e=="object"&&!!e[Symbol.iterator]().next().done,Aw=class extends pV.NodeBase{constructor(t,r){super(t),Object.defineProperty(this,"schema",{value:r,configurable:!0,enumerable:!1,writable:!0})}clone(t){let r=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return t&&(r.schema=t),r.items=r.items.map(n=>Ai.isNode(n)||Ai.isPair(n)?n.clone(t):n),this.range&&(r.range=this.range.slice()),r}addIn(t,r){if(GE(t))this.add(r);else{let[n,...i]=t,o=this.get(n,!0);if(Ai.isCollection(o))o.addIn(i,r);else if(o===void 0&&this.schema)this.set(n,bw(this.schema,i,r));else throw new Error(`Expected YAML collection at ${n}. Remaining path: ${i}`)}}deleteIn(t){let[r,...n]=t;if(n.length===0)return this.delete(r);let i=this.get(r,!0);if(Ai.isCollection(i))return i.deleteIn(n);throw new Error(`Expected YAML collection at ${r}. Remaining path: ${n}`)}getIn(t,r){let[n,...i]=t,o=this.get(n,!0);return i.length===0?!r&&Ai.isScalar(o)?o.value:o:Ai.isCollection(o)?o.getIn(i,r):void 0}hasAllNullValues(t){return this.items.every(r=>{if(!Ai.isPair(r))return!1;let n=r.value;return n==null||t&&Ai.isScalar(n)&&n.value==null&&!n.commentBefore&&!n.comment&&!n.tag})}hasIn(t){let[r,...n]=t;if(n.length===0)return this.has(r);let i=this.get(r,!0);return Ai.isCollection(i)?i.hasIn(n):!1}setIn(t,r){let[n,...i]=t;if(i.length===0)this.set(n,r);else{let o=this.get(n,!0);if(Ai.isCollection(o))o.setIn(i,r);else if(o===void 0&&this.schema)this.set(n,bw(this.schema,i,r));else throw new Error(`Expected YAML collection at ${n}. Remaining path: ${i}`)}}};ap.Collection=Aw;ap.collectionFromPath=bw;ap.isEmptyPath=GE});var Xl=$(cp=>{"use strict";var mV=e=>e.replace(/^(?!$)(?: $)?/gm,"#");function Rw(e,t){return/^\n+$/.test(e)?e.substring(1):t?e.replace(/^(?! *$)/gm,t):e}var hV=(e,t,r)=>e.endsWith(`
|
|
6
|
+
`)?Rw(r,t):r.includes(`
|
|
7
|
+
`)?`
|
|
8
|
+
`+Rw(r,t):(e.endsWith(" ")?"":" ")+r;cp.indentComment=Rw;cp.lineComment=hV;cp.stringifyComment=mV});var XE=$(Zl=>{"use strict";var gV="flow",Nw="block",lp="quoted";function vV(e,t,r="flow",{indentAtStart:n,lineWidth:i=80,minContentWidth:o=20,onFold:a,onOverflow:s}={}){if(!i||i<0)return e;i<o&&(o=0);let c=Math.max(1+o,1+i-t.length);if(e.length<=c)return e;let l=[],u={},f=i-t.length;typeof n=="number"&&(n>i-Math.max(2,o)?l.push(0):f=i-n);let d,p,m=!1,h=-1,g=-1,v=-1;r===Nw&&(h=YE(e,h,t.length),h!==-1&&(f=h+c));for(let y;y=e[h+=1];){if(r===lp&&y==="\\"){switch(g=h,e[h+1]){case"x":h+=3;break;case"u":h+=5;break;case"U":h+=9;break;default:h+=1}v=h}if(y===`
|
|
9
|
+
`)r===Nw&&(h=YE(e,h,t.length)),f=h+t.length+c,d=void 0;else{if(y===" "&&p&&p!==" "&&p!==`
|
|
10
|
+
`&&p!==" "){let R=e[h+1];R&&R!==" "&&R!==`
|
|
11
|
+
`&&R!==" "&&(d=h)}if(h>=f)if(d)l.push(d),f=d+c,d=void 0;else if(r===lp){for(;p===" "||p===" ";)p=y,y=e[h+=1],m=!0;let R=h>v+1?h-2:g-1;if(u[R])return e;l.push(R),u[R]=!0,f=R+c,d=void 0}else m=!0}p=y}if(m&&s&&s(),l.length===0)return e;a&&a();let w=e.slice(0,l[0]);for(let y=0;y<l.length;++y){let R=l[y],N=l[y+1]||e.length;R===0?w=`
|
|
12
|
+
${t}${e.slice(0,N)}`:(r===lp&&u[R]&&(w+=`${e[R]}\\`),w+=`
|
|
13
|
+
${t}${e.slice(R+1,N)}`)}return w}function YE(e,t,r){let n=t,i=t+1,o=e[i];for(;o===" "||o===" ";)if(t<i+r)o=e[++t];else{do o=e[++t];while(o&&o!==`
|
|
14
|
+
`);n=t,i=t+1,o=e[i]}return n}Zl.FOLD_BLOCK=Nw;Zl.FOLD_FLOW=gV;Zl.FOLD_QUOTED=lp;Zl.foldFlowLines=vV});var tu=$(ZE=>{"use strict";var Kn=jt(),Po=XE(),dp=(e,t)=>({indentAtStart:t?e.indent.length:e.indentAtStart,lineWidth:e.options.lineWidth,minContentWidth:e.options.minContentWidth}),fp=e=>/^(%|---|\.\.\.)/m.test(e);function wV(e,t,r){if(!t||t<0)return!1;let n=t-r,i=e.length;if(i<=n)return!1;for(let o=0,a=0;o<i;++o)if(e[o]===`
|
|
15
|
+
`){if(o-a>n)return!0;if(a=o+1,i-a<=n)return!1}return!0}function eu(e,t){let r=JSON.stringify(e);if(t.options.doubleQuotedAsJSON)return r;let{implicitKey:n}=t,i=t.options.doubleQuotedMinMultiLineLength,o=t.indent||(fp(e)?" ":""),a="",s=0;for(let c=0,l=r[c];l;l=r[++c])if(l===" "&&r[c+1]==="\\"&&r[c+2]==="n"&&(a+=r.slice(s,c)+"\\ ",c+=1,s=c,l="\\"),l==="\\")switch(r[c+1]){case"u":{a+=r.slice(s,c);let u=r.substr(c+2,4);switch(u){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:u.substr(0,2)==="00"?a+="\\x"+u.substr(2):a+=r.substr(c,6)}c+=5,s=c+1}break;case"n":if(n||r[c+2]==='"'||r.length<i)c+=1;else{for(a+=r.slice(s,c)+`
|
|
16
|
+
|
|
17
|
+
`;r[c+2]==="\\"&&r[c+3]==="n"&&r[c+4]!=='"';)a+=`
|
|
18
|
+
`,c+=2;a+=o,r[c+2]===" "&&(a+="\\"),c+=1,s=c+1}break;default:c+=1}return a=s?a+r.slice(s):r,n?a:Po.foldFlowLines(a,o,Po.FOLD_QUOTED,dp(t,!1))}function Sw(e,t){if(t.options.singleQuote===!1||t.implicitKey&&e.includes(`
|
|
19
|
+
`)||/[ \t]\n|\n[ \t]/.test(e))return eu(e,t);let r=t.indent||(fp(e)?" ":""),n="'"+e.replace(/'/g,"''").replace(/\n+/g,`$&
|
|
20
|
+
${r}`)+"'";return t.implicitKey?n:Po.foldFlowLines(n,r,Po.FOLD_FLOW,dp(t,!1))}function ic(e,t){let{singleQuote:r}=t.options,n;if(r===!1)n=eu;else{let i=e.includes('"'),o=e.includes("'");i&&!o?n=Sw:o&&!i?n=eu:n=r?Sw:eu}return n(e,t)}var Ew;try{Ew=new RegExp(`(^|(?<!
|
|
21
|
+
))
|
|
22
|
+
+(?!
|
|
23
|
+
|$)`,"g")}catch{Ew=/\n+(?!\n|$)/g}function up({comment:e,type:t,value:r},n,i,o){let{blockQuote:a,commentString:s,lineWidth:c}=n.options;if(!a||/\n[\t ]+$/.test(r))return ic(r,n);let l=n.indent||(n.forceBlockIndent||fp(r)?" ":""),u=a==="literal"?!0:a==="folded"||t===Kn.Scalar.BLOCK_FOLDED?!1:t===Kn.Scalar.BLOCK_LITERAL?!0:!wV(r,c,l.length);if(!r)return u?`|
|
|
24
|
+
`:`>
|
|
25
|
+
`;let f,d;for(d=r.length;d>0;--d){let N=r[d-1];if(N!==`
|
|
26
|
+
`&&N!==" "&&N!==" ")break}let p=r.substring(d),m=p.indexOf(`
|
|
27
|
+
`);m===-1?f="-":r===p||m!==p.length-1?(f="+",o&&o()):f="",p&&(r=r.slice(0,-p.length),p[p.length-1]===`
|
|
28
|
+
`&&(p=p.slice(0,-1)),p=p.replace(Ew,`$&${l}`));let h=!1,g,v=-1;for(g=0;g<r.length;++g){let N=r[g];if(N===" ")h=!0;else if(N===`
|
|
29
|
+
`)v=g;else break}let w=r.substring(0,v<g?v+1:g);w&&(r=r.substring(w.length),w=w.replace(/\n+/g,`$&${l}`));let R=(h?l?"2":"1":"")+f;if(e&&(R+=" "+s(e.replace(/ ?[\r\n]+/g," ")),i&&i()),!u){let N=r.replace(/\n+/g,`
|
|
30
|
+
$&`).replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g,"$1$2").replace(/\n+/g,`$&${l}`),b=!1,E=dp(n,!0);a!=="folded"&&t!==Kn.Scalar.BLOCK_FOLDED&&(E.onOverflow=()=>{b=!0});let I=Po.foldFlowLines(`${w}${N}${p}`,l,Po.FOLD_BLOCK,E);if(!b)return`>${R}
|
|
31
|
+
${l}${I}`}return r=r.replace(/\n+/g,`$&${l}`),`|${R}
|
|
32
|
+
${l}${w}${r}${p}`}function yV(e,t,r,n){let{type:i,value:o}=e,{actualString:a,implicitKey:s,indent:c,indentStep:l,inFlow:u}=t;if(s&&o.includes(`
|
|
33
|
+
`)||u&&/[[\]{},]/.test(o))return ic(o,t);if(/^[\n\t ,[\]{}#&*!|>'"%@`]|^[?-]$|^[?-][ \t]|[\n:][ \t]|[ \t]\n|[\n\t ]#|[\n\t :]$/.test(o))return s||u||!o.includes(`
|
|
34
|
+
`)?ic(o,t):up(e,t,r,n);if(!s&&!u&&i!==Kn.Scalar.PLAIN&&o.includes(`
|
|
35
|
+
`))return up(e,t,r,n);if(fp(o)){if(c==="")return t.forceBlockIndent=!0,up(e,t,r,n);if(s&&c===l)return ic(o,t)}let f=o.replace(/\n+/g,`$&
|
|
36
|
+
${c}`);if(a){let d=h=>h.default&&h.tag!=="tag:yaml.org,2002:str"&&h.test?.test(f),{compat:p,tags:m}=t.doc.schema;if(m.some(d)||p?.some(d))return ic(o,t)}return s?f:Po.foldFlowLines(f,c,Po.FOLD_FLOW,dp(t,!1))}function kV(e,t,r,n){let{implicitKey:i,inFlow:o}=t,a=typeof e.value=="string"?e:Object.assign({},e,{value:String(e.value)}),{type:s}=e;s!==Kn.Scalar.QUOTE_DOUBLE&&/[\x00-\x08\x0b-\x1f\x7f-\x9f\u{D800}-\u{DFFF}]/u.test(a.value)&&(s=Kn.Scalar.QUOTE_DOUBLE);let c=u=>{switch(u){case Kn.Scalar.BLOCK_FOLDED:case Kn.Scalar.BLOCK_LITERAL:return i||o?ic(a.value,t):up(a,t,r,n);case Kn.Scalar.QUOTE_DOUBLE:return eu(a.value,t);case Kn.Scalar.QUOTE_SINGLE:return Sw(a.value,t);case Kn.Scalar.PLAIN:return yV(a,t,r,n);default:return null}},l=c(s);if(l===null){let{defaultKeyType:u,defaultStringType:f}=t.options,d=i&&u||f;if(l=c(d),l===null)throw new Error(`Unsupported default string type ${d}`)}return l}ZE.stringifyString=kV});var ru=$(Cw=>{"use strict";var bV=np(),To=De(),AV=Xl(),RV=tu();function NV(e,t){let r=Object.assign({blockQuote:!0,commentString:AV.stringifyComment,defaultKeyType:null,defaultStringType:"PLAIN",directives:null,doubleQuotedAsJSON:!1,doubleQuotedMinMultiLineLength:40,falseStr:"false",flowCollectionPadding:!0,indentSeq:!0,lineWidth:80,minContentWidth:20,nullStr:"null",simpleKeys:!1,singleQuote:null,trailingComma:!1,trueStr:"true",verifyAliasOrder:!0},e.schema.toStringOptions,t),n;switch(r.collectionStyle){case"block":n=!1;break;case"flow":n=!0;break;default:n=null}return{anchors:new Set,doc:e,flowCollectionPadding:r.flowCollectionPadding?" ":"",indent:"",indentStep:typeof r.indent=="number"?" ".repeat(r.indent):" ",inFlow:n,options:r}}function SV(e,t){if(t.tag){let i=e.filter(o=>o.tag===t.tag);if(i.length>0)return i.find(o=>o.format===t.format)??i[0]}let r,n;if(To.isScalar(t)){n=t.value;let i=e.filter(o=>o.identify?.(n));if(i.length>1){let o=i.filter(a=>a.test);o.length>0&&(i=o)}r=i.find(o=>o.format===t.format)??i.find(o=>!o.format)}else n=t,r=e.find(i=>i.nodeClass&&n instanceof i.nodeClass);if(!r){let i=n?.constructor?.name??(n===null?"null":typeof n);throw new Error(`Tag not resolved for ${i} value`)}return r}function EV(e,t,{anchors:r,doc:n}){if(!n.directives)return"";let i=[],o=(To.isScalar(e)||To.isCollection(e))&&e.anchor;o&&bV.anchorIsValid(o)&&(r.add(o),i.push(`&${o}`));let a=e.tag??(t.default?null:t.tag);return a&&i.push(n.directives.tagString(a)),i.join(" ")}function CV(e,t,r,n){if(To.isPair(e))return e.toString(t,r,n);if(To.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=To.isNode(e)?e:t.doc.createNode(e,{onTagObj:c=>i=c});i??(i=SV(t.doc.schema.tags,o));let a=EV(o,i,t);a.length>0&&(t.indentAtStart=(t.indentAtStart??0)+a.length+1);let s=typeof i.stringify=="function"?i.stringify(o,t,r,n):To.isScalar(o)?RV.stringifyString(o,t,r,n):o.toString(t,r,n);return a?To.isScalar(o)||s[0]==="{"||s[0]==="["?`${a} ${s}`:`${a}
|
|
37
|
+
${t.indent}${s}`:s}Cw.createStringifyContext=NV;Cw.stringify=CV});var nC=$(rC=>{"use strict";var Zi=De(),eC=jt(),tC=ru(),nu=Xl();function _V({key:e,value:t},r,n,i){let{allNullValues:o,doc:a,indent:s,indentStep:c,options:{commentString:l,indentSeq:u,simpleKeys:f}}=r,d=Zi.isNode(e)&&e.comment||null;if(f){if(d)throw new Error("With simple keys, key nodes cannot have comments");if(Zi.isCollection(e)||!Zi.isNode(e)&&typeof e=="object"){let E="With simple keys, collection cannot be used as a key value";throw new Error(E)}}let p=!f&&(!e||d&&t==null&&!r.inFlow||Zi.isCollection(e)||(Zi.isScalar(e)?e.type===eC.Scalar.BLOCK_FOLDED||e.type===eC.Scalar.BLOCK_LITERAL:typeof e=="object"));r=Object.assign({},r,{allNullValues:!1,implicitKey:!p&&(f||!o),indent:s+c});let m=!1,h=!1,g=tC.stringify(e,r,()=>m=!0,()=>h=!0);if(!p&&!r.inFlow&&g.length>1024){if(f)throw new Error("With simple keys, single line scalar must not span more than 1024 characters");p=!0}if(r.inFlow){if(o||t==null)return m&&n&&n(),g===""?"?":p?`? ${g}`:g}else if(o&&!f||t==null&&p)return g=`? ${g}`,d&&!m?g+=nu.lineComment(g,r.indent,l(d)):h&&i&&i(),g;m&&(d=null),p?(d&&(g+=nu.lineComment(g,r.indent,l(d))),g=`? ${g}
|
|
38
|
+
${s}:`):(g=`${g}:`,d&&(g+=nu.lineComment(g,r.indent,l(d))));let v,w,y;Zi.isNode(t)?(v=!!t.spaceBefore,w=t.commentBefore,y=t.comment):(v=!1,w=null,y=null,t&&typeof t=="object"&&(t=a.createNode(t))),r.implicitKey=!1,!p&&!d&&Zi.isScalar(t)&&(r.indentAtStart=g.length+1),h=!1,!u&&c.length>=2&&!r.inFlow&&!p&&Zi.isSeq(t)&&!t.flow&&!t.tag&&!t.anchor&&(r.indent=r.indent.substring(2));let R=!1,N=tC.stringify(t,r,()=>R=!0,()=>h=!0),b=" ";if(d||v||w){if(b=v?`
|
|
39
|
+
`:"",w){let E=l(w);b+=`
|
|
40
|
+
${nu.indentComment(E,r.indent)}`}N===""&&!r.inFlow?b===`
|
|
41
|
+
`&&y&&(b=`
|
|
42
|
+
|
|
43
|
+
`):b+=`
|
|
44
|
+
${r.indent}`}else if(!p&&Zi.isCollection(t)){let E=N[0],I=N.indexOf(`
|
|
45
|
+
`),W=I!==-1,F=r.inFlow??t.flow??t.items.length===0;if(W||!F){let G=!1;if(W&&(E==="&"||E==="!")){let Z=N.indexOf(" ");E==="&"&&Z!==-1&&Z<I&&N[Z+1]==="!"&&(Z=N.indexOf(" ",Z+1)),(Z===-1||I<Z)&&(G=!0)}G||(b=`
|
|
46
|
+
${r.indent}`)}}else(N===""||N[0]===`
|
|
47
|
+
`)&&(b="");return g+=b+N,r.inFlow?R&&n&&n():y&&!R?g+=nu.lineComment(g,r.indent,l(y)):h&&i&&i(),g}rC.stringifyPair=_V});var Iw=$(_w=>{"use strict";var iC=Xf("process");function IV(e,...t){e==="debug"&&console.log(...t)}function xV(e,t){(e==="debug"||e==="warn")&&(typeof iC.emitWarning=="function"?iC.emitWarning(t):console.warn(t))}_w.debug=IV;_w.warn=xV});var vp=$(gp=>{"use strict";var hp=De(),oC=jt(),pp="<<",mp={identify:e=>e===pp||typeof e=="symbol"&&e.description===pp,default:"key",tag:"tag:yaml.org,2002:merge",test:/^<<$/,resolve:()=>Object.assign(new oC.Scalar(Symbol(pp)),{addToJSMap:aC}),stringify:()=>pp},PV=(e,t)=>(mp.identify(t)||hp.isScalar(t)&&(!t.type||t.type===oC.Scalar.PLAIN)&&mp.identify(t.value))&&e?.doc.schema.tags.some(r=>r.tag===mp.tag&&r.default);function aC(e,t,r){let n=sC(e,r);if(hp.isSeq(n))for(let i of n.items)xw(e,t,i);else if(Array.isArray(n))for(let i of n)xw(e,t,i);else xw(e,t,n)}function xw(e,t,r){let n=sC(e,r);if(!hp.isMap(n))throw new Error("Merge sources must be maps or map aliases");let i=n.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 sC(e,t){return e&&hp.isAlias(t)?t.resolve(e.doc,e):t}gp.addMergeToJSMap=aC;gp.isMergeKey=PV;gp.merge=mp});var Tw=$(uC=>{"use strict";var TV=Iw(),cC=vp(),OV=ru(),lC=De(),Pw=Io();function jV(e,t,{key:r,value:n}){if(lC.isNode(r)&&r.addToJSMap)r.addToJSMap(e,t,n);else if(cC.isMergeKey(e,r))cC.addMergeToJSMap(e,t,n);else{let i=Pw.toJS(r,"",e);if(t instanceof Map)t.set(i,Pw.toJS(n,i,e));else if(t instanceof Set)t.add(i);else{let o=$V(r,i,e),a=Pw.toJS(n,o,e);o in t?Object.defineProperty(t,o,{value:a,writable:!0,enumerable:!0,configurable:!0}):t[o]=a}}return t}function $V(e,t,r){if(t===null)return"";if(typeof t!="object")return String(t);if(lC.isNode(e)&&r?.doc){let n=OV.createStringifyContext(r.doc,{});n.anchors=new Set;for(let o of r.anchors.keys())n.anchors.add(o.anchor);n.inFlow=!0,n.inStringifyKey=!0;let i=e.toString(n);if(!r.mapKeyWarned){let o=JSON.stringify(i);o.length>40&&(o=o.substring(0,36)+'..."'),TV.warn(r.doc.options.logLevel,`Keys with collection values will be stringified due to JS Object restrictions: ${o}. Set mapAsMap: true to use object keys.`),r.mapKeyWarned=!0}return i}return JSON.stringify(t)}uC.addPairToJSMap=jV});var Oo=$(Ow=>{"use strict";var dC=Yl(),DV=nC(),BV=Tw(),wp=De();function WV(e,t,r){let n=dC.createNode(e,void 0,r),i=dC.createNode(t,void 0,r);return new yp(n,i)}var yp=class e{constructor(t,r=null){Object.defineProperty(this,wp.NODE_TYPE,{value:wp.PAIR}),this.key=t,this.value=r}clone(t){let{key:r,value:n}=this;return wp.isNode(r)&&(r=r.clone(t)),wp.isNode(n)&&(n=n.clone(t)),new e(r,n)}toJSON(t,r){let n=r?.mapAsMap?new Map:{};return BV.addPairToJSMap(r,n,this)}toString(t,r,n){return t?.doc?DV.stringifyPair(this,t,r,n):JSON.stringify(this)}};Ow.Pair=yp;Ow.createPair=WV});var jw=$(pC=>{"use strict";var ja=De(),fC=ru(),kp=Xl();function qV(e,t,r){return(t.inFlow??e.flow?VV:LV)(e,t,r)}function LV({comment:e,items:t},r,{blockItemPrefix:n,flowChars:i,itemIndent:o,onChompKeep:a,onComment:s}){let{indent:c,options:{commentString:l}}=r,u=Object.assign({},r,{indent:o,type:null}),f=!1,d=[];for(let m=0;m<t.length;++m){let h=t[m],g=null;if(ja.isNode(h))!f&&h.spaceBefore&&d.push(""),bp(r,d,h.commentBefore,f),h.comment&&(g=h.comment);else if(ja.isPair(h)){let w=ja.isNode(h.key)?h.key:null;w&&(!f&&w.spaceBefore&&d.push(""),bp(r,d,w.commentBefore,f))}f=!1;let v=fC.stringify(h,u,()=>g=null,()=>f=!0);g&&(v+=kp.lineComment(v,o,l(g))),f&&g&&(f=!1),d.push(n+v)}let p;if(d.length===0)p=i.start+i.end;else{p=d[0];for(let m=1;m<d.length;++m){let h=d[m];p+=h?`
|
|
48
|
+
${c}${h}`:`
|
|
49
|
+
`}}return e?(p+=`
|
|
50
|
+
`+kp.indentComment(l(e),c),s&&s()):f&&a&&a(),p}function VV({items:e},t,{flowChars:r,itemIndent:n}){let{indent:i,indentStep:o,flowCollectionPadding:a,options:{commentString:s}}=t;n+=o;let c=Object.assign({},t,{indent:n,inFlow:!0,type:null}),l=!1,u=0,f=[];for(let m=0;m<e.length;++m){let h=e[m],g=null;if(ja.isNode(h))h.spaceBefore&&f.push(""),bp(t,f,h.commentBefore,!1),h.comment&&(g=h.comment);else if(ja.isPair(h)){let w=ja.isNode(h.key)?h.key:null;w&&(w.spaceBefore&&f.push(""),bp(t,f,w.commentBefore,!1),w.comment&&(l=!0));let y=ja.isNode(h.value)?h.value:null;y?(y.comment&&(g=y.comment),y.commentBefore&&(l=!0)):h.value==null&&w?.comment&&(g=w.comment)}g&&(l=!0);let v=fC.stringify(h,c,()=>g=null);l||(l=f.length>u||v.includes(`
|
|
51
|
+
`)),m<e.length-1?v+=",":t.options.trailingComma&&(t.options.lineWidth>0&&(l||(l=f.reduce((w,y)=>w+y.length+2,2)+(v.length+2)>t.options.lineWidth)),l&&(v+=",")),g&&(v+=kp.lineComment(v,n,s(g))),f.push(v),u=f.length}let{start:d,end:p}=r;if(f.length===0)return d+p;if(!l){let m=f.reduce((h,g)=>h+g.length+2,2);l=t.options.lineWidth>0&&m>t.options.lineWidth}if(l){let m=d;for(let h of f)m+=h?`
|
|
52
|
+
${o}${i}${h}`:`
|
|
53
|
+
`;return`${m}
|
|
54
|
+
${i}${p}`}else return`${d}${a}${f.join(" ")}${a}${p}`}function bp({indent:e,options:{commentString:t}},r,n,i){if(n&&i&&(n=n.replace(/^\n+/,"")),n){let o=kp.indentComment(t(n),e);r.push(o.trimStart())}}pC.stringifyCollection=qV});var $o=$(Dw=>{"use strict";var MV=jw(),FV=Tw(),HV=sp(),jo=De(),Ap=Oo(),QV=jt();function iu(e,t){let r=jo.isScalar(t)?t.value:t;for(let n of e)if(jo.isPair(n)&&(n.key===t||n.key===r||jo.isScalar(n.key)&&n.key.value===r))return n}var $w=class extends HV.Collection{static get tagName(){return"tag:yaml.org,2002:map"}constructor(t){super(jo.MAP,t),this.items=[]}static from(t,r,n){let{keepUndefined:i,replacer:o}=n,a=new this(t),s=(c,l)=>{if(typeof o=="function")l=o.call(r,c,l);else if(Array.isArray(o)&&!o.includes(c))return;(l!==void 0||i)&&a.items.push(Ap.createPair(c,l,n))};if(r instanceof Map)for(let[c,l]of r)s(c,l);else if(r&&typeof r=="object")for(let c of Object.keys(r))s(c,r[c]);return typeof t.sortMapEntries=="function"&&a.items.sort(t.sortMapEntries),a}add(t,r){let n;jo.isPair(t)?n=t:!t||typeof t!="object"||!("key"in t)?n=new Ap.Pair(t,t?.value):n=new Ap.Pair(t.key,t.value);let i=iu(this.items,n.key),o=this.schema?.sortMapEntries;if(i){if(!r)throw new Error(`Key ${n.key} already set`);jo.isScalar(i.value)&&QV.isScalarValue(n.value)?i.value.value=n.value:i.value=n.value}else if(o){let a=this.items.findIndex(s=>o(n,s)<0);a===-1?this.items.push(n):this.items.splice(a,0,n)}else this.items.push(n)}delete(t){let r=iu(this.items,t);return r?this.items.splice(this.items.indexOf(r),1).length>0:!1}get(t,r){let i=iu(this.items,t)?.value;return(!r&&jo.isScalar(i)?i.value:i)??void 0}has(t){return!!iu(this.items,t)}set(t,r){this.add(new Ap.Pair(t,r),!0)}toJSON(t,r,n){let i=n?new n:r?.mapAsMap?new Map:{};r?.onCreate&&r.onCreate(i);for(let o of this.items)FV.addPairToJSMap(r,i,o);return i}toString(t,r,n){if(!t)return JSON.stringify(this);for(let i of this.items)if(!jo.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})),MV.stringifyCollection(this,t,{blockItemPrefix:"",flowChars:{start:"{",end:"}"},itemIndent:t.indent||"",onChompKeep:n,onComment:r})}};Dw.YAMLMap=$w;Dw.findPair=iu});var oc=$(hC=>{"use strict";var UV=De(),mC=$o(),JV={collection:"map",default:!0,nodeClass:mC.YAMLMap,tag:"tag:yaml.org,2002:map",resolve(e,t){return UV.isMap(e)||t("Expected a mapping for this tag"),e},createNode:(e,t,r)=>mC.YAMLMap.from(e,t,r)};hC.map=JV});var Do=$(gC=>{"use strict";var zV=Yl(),KV=jw(),GV=sp(),Np=De(),YV=jt(),XV=Io(),Bw=class extends GV.Collection{static get tagName(){return"tag:yaml.org,2002:seq"}constructor(t){super(Np.SEQ,t),this.items=[]}add(t){this.items.push(t)}delete(t){let r=Rp(t);return typeof r!="number"?!1:this.items.splice(r,1).length>0}get(t,r){let n=Rp(t);if(typeof n!="number")return;let i=this.items[n];return!r&&Np.isScalar(i)?i.value:i}has(t){let r=Rp(t);return typeof r=="number"&&r<this.items.length}set(t,r){let n=Rp(t);if(typeof n!="number")throw new Error(`Expected a valid index, not ${t}.`);let i=this.items[n];Np.isScalar(i)&&YV.isScalarValue(r)?i.value=r:this.items[n]=r}toJSON(t,r){let n=[];r?.onCreate&&r.onCreate(n);let i=0;for(let o of this.items)n.push(XV.toJS(o,String(i++),r));return n}toString(t,r,n){return t?KV.stringifyCollection(this,t,{blockItemPrefix:"- ",flowChars:{start:"[",end:"]"},itemIndent:(t.indent||"")+" ",onChompKeep:n,onComment:r}):JSON.stringify(this)}static from(t,r,n){let{replacer:i}=n,o=new this(t);if(r&&Symbol.iterator in Object(r)){let a=0;for(let s of r){if(typeof i=="function"){let c=r instanceof Set?s:String(a++);s=i.call(r,c,s)}o.items.push(zV.createNode(s,void 0,n))}}return o}};function Rp(e){let t=Np.isScalar(e)?e.value:e;return t&&typeof t=="string"&&(t=Number(t)),typeof t=="number"&&Number.isInteger(t)&&t>=0?t:null}gC.YAMLSeq=Bw});var ac=$(wC=>{"use strict";var ZV=De(),vC=Do(),eM={collection:"seq",default:!0,nodeClass:vC.YAMLSeq,tag:"tag:yaml.org,2002:seq",resolve(e,t){return ZV.isSeq(e)||t("Expected a sequence for this tag"),e},createNode:(e,t,r)=>vC.YAMLSeq.from(e,t,r)};wC.seq=eM});var ou=$(yC=>{"use strict";var tM=tu(),rM={identify:e=>typeof e=="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:e=>e,stringify(e,t,r,n){return t=Object.assign({actualString:!0},t),tM.stringifyString(e,t,r,n)}};yC.string=rM});var Sp=$(AC=>{"use strict";var kC=jt(),bC={identify:e=>e==null,createNode:()=>new kC.Scalar(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^(?:~|[Nn]ull|NULL)?$/,resolve:()=>new kC.Scalar(null),stringify:({source:e},t)=>typeof e=="string"&&bC.test.test(e)?e:t.options.nullStr};AC.nullTag=bC});var Ww=$(NC=>{"use strict";var nM=jt(),RC={identify:e=>typeof e=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:[Tt]rue|TRUE|[Ff]alse|FALSE)$/,resolve:e=>new nM.Scalar(e[0]==="t"||e[0]==="T"),stringify({source:e,value:t},r){if(e&&RC.test.test(e)){let n=e[0]==="t"||e[0]==="T";if(t===n)return e}return t?r.options.trueStr:r.options.falseStr}};NC.boolTag=RC});var sc=$(SC=>{"use strict";function iM({format:e,minFractionDigits:t,tag:r,value:n}){if(typeof n=="bigint")return String(n);let i=typeof n=="number"?n:Number(n);if(!isFinite(i))return isNaN(i)?".nan":i<0?"-.inf":".inf";let o=Object.is(n,-0)?"-0":JSON.stringify(n);if(!e&&t&&(!r||r==="tag:yaml.org,2002:float")&&/^-?\d/.test(o)&&!o.includes("e")){let a=o.indexOf(".");a<0&&(a=o.length,o+=".");let s=t-(o.length-a-1);for(;s-- >0;)o+="0"}return o}SC.stringifyNumber=iM});var Lw=$(Ep=>{"use strict";var oM=jt(),qw=sc(),aM={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:qw.stringifyNumber},sM={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():qw.stringifyNumber(e)}},cM={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 oM.Scalar(parseFloat(e)),r=e.indexOf(".");return r!==-1&&e[e.length-1]==="0"&&(t.minFractionDigits=e.length-r-1),t},stringify:qw.stringifyNumber};Ep.float=cM;Ep.floatExp=sM;Ep.floatNaN=aM});var Mw=$(_p=>{"use strict";var EC=sc(),Cp=e=>typeof e=="bigint"||Number.isInteger(e),Vw=(e,t,r,{intAsBigInt:n})=>n?BigInt(e):parseInt(e.substring(t),r);function CC(e,t,r){let{value:n}=e;return Cp(n)&&n>=0?r+n.toString(t):EC.stringifyNumber(e)}var lM={identify:e=>Cp(e)&&e>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^0o[0-7]+$/,resolve:(e,t,r)=>Vw(e,2,8,r),stringify:e=>CC(e,8,"0o")},uM={identify:Cp,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9]+$/,resolve:(e,t,r)=>Vw(e,0,10,r),stringify:EC.stringifyNumber},dM={identify:e=>Cp(e)&&e>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^0x[0-9a-fA-F]+$/,resolve:(e,t,r)=>Vw(e,2,16,r),stringify:e=>CC(e,16,"0x")};_p.int=uM;_p.intHex=dM;_p.intOct=lM});var IC=$(_C=>{"use strict";var fM=oc(),pM=Sp(),mM=ac(),hM=ou(),gM=Ww(),Fw=Lw(),Hw=Mw(),vM=[fM.map,mM.seq,hM.string,pM.nullTag,gM.boolTag,Hw.intOct,Hw.int,Hw.intHex,Fw.floatNaN,Fw.floatExp,Fw.float];_C.schema=vM});var TC=$(PC=>{"use strict";var wM=jt(),yM=oc(),kM=ac();function xC(e){return typeof e=="bigint"||Number.isInteger(e)}var Ip=({value:e})=>JSON.stringify(e),bM=[{identify:e=>typeof e=="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:e=>e,stringify:Ip},{identify:e=>e==null,createNode:()=>new wM.Scalar(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^null$/,resolve:()=>null,stringify:Ip},{identify:e=>typeof e=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^true$|^false$/,resolve:e=>e==="true",stringify:Ip},{identify:xC,default:!0,tag:"tag:yaml.org,2002:int",test:/^-?(?:0|[1-9][0-9]*)$/,resolve:(e,t,{intAsBigInt:r})=>r?BigInt(e):parseInt(e,10),stringify:({value:e})=>xC(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:Ip}],AM={default:!0,tag:"",test:/^/,resolve(e,t){return t(`Unresolved plain scalar ${JSON.stringify(e)}`),e}},RM=[yM.map,kM.seq].concat(bM,AM);PC.schema=RM});var Uw=$(OC=>{"use strict";var au=Xf("buffer"),Qw=jt(),NM=tu(),SM={identify:e=>e instanceof Uint8Array,default:!1,tag:"tag:yaml.org,2002:binary",resolve(e,t){if(typeof au.Buffer=="function")return au.Buffer.from(e,"base64");if(typeof atob=="function"){let r=atob(e.replace(/[\n\r]/g,"")),n=new Uint8Array(r.length);for(let i=0;i<r.length;++i)n[i]=r.charCodeAt(i);return n}else return t("This environment does not support reading binary tags; either Buffer or atob is required"),e},stringify({comment:e,type:t,value:r},n,i,o){if(!r)return"";let a=r,s;if(typeof au.Buffer=="function")s=a instanceof au.Buffer?a.toString("base64"):au.Buffer.from(a.buffer).toString("base64");else if(typeof btoa=="function"){let c="";for(let l=0;l<a.length;++l)c+=String.fromCharCode(a[l]);s=btoa(c)}else throw new Error("This environment does not support writing binary tags; either Buffer or btoa is required");if(t??(t=Qw.Scalar.BLOCK_LITERAL),t!==Qw.Scalar.QUOTE_DOUBLE){let c=Math.max(n.options.lineWidth-n.indent.length,n.options.minContentWidth),l=Math.ceil(s.length/c),u=new Array(l);for(let f=0,d=0;f<l;++f,d+=c)u[f]=s.substr(d,c);s=u.join(t===Qw.Scalar.BLOCK_LITERAL?`
|
|
55
|
+
`:" ")}return NM.stringifyString({comment:e,type:t,value:s},n,i,o)}};OC.binary=SM});var Tp=$(Pp=>{"use strict";var xp=De(),Jw=Oo(),EM=jt(),CM=Do();function jC(e,t){if(xp.isSeq(e))for(let r=0;r<e.items.length;++r){let n=e.items[r];if(!xp.isPair(n)){if(xp.isMap(n)){n.items.length>1&&t("Each pair must have its own sequence indicator");let i=n.items[0]||new Jw.Pair(new EM.Scalar(null));if(n.commentBefore&&(i.key.commentBefore=i.key.commentBefore?`${n.commentBefore}
|
|
56
|
+
${i.key.commentBefore}`:n.commentBefore),n.comment){let o=i.value??i.key;o.comment=o.comment?`${n.comment}
|
|
57
|
+
${o.comment}`:n.comment}n=i}e.items[r]=xp.isPair(n)?n:new Jw.Pair(n)}}else t("Expected a sequence for this tag");return e}function $C(e,t,r){let{replacer:n}=r,i=new CM.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 n=="function"&&(a=n.call(t,String(o++),a));let s,c;if(Array.isArray(a))if(a.length===2)s=a[0],c=a[1];else throw new TypeError(`Expected [key, value] tuple: ${a}`);else if(a&&a instanceof Object){let l=Object.keys(a);if(l.length===1)s=l[0],c=a[s];else throw new TypeError(`Expected tuple with one key, not ${l.length} keys`)}else s=a;i.items.push(Jw.createPair(s,c,r))}return i}var _M={collection:"seq",default:!1,tag:"tag:yaml.org,2002:pairs",resolve:jC,createNode:$C};Pp.createPairs=$C;Pp.pairs=_M;Pp.resolvePairs=jC});var Gw=$(Kw=>{"use strict";var DC=De(),zw=Io(),su=$o(),IM=Do(),BC=Tp(),$a=class e extends IM.YAMLSeq{constructor(){super(),this.add=su.YAMLMap.prototype.add.bind(this),this.delete=su.YAMLMap.prototype.delete.bind(this),this.get=su.YAMLMap.prototype.get.bind(this),this.has=su.YAMLMap.prototype.has.bind(this),this.set=su.YAMLMap.prototype.set.bind(this),this.tag=e.tag}toJSON(t,r){if(!r)return super.toJSON(t);let n=new Map;r?.onCreate&&r.onCreate(n);for(let i of this.items){let o,a;if(DC.isPair(i)?(o=zw.toJS(i.key,"",r),a=zw.toJS(i.value,o,r)):o=zw.toJS(i,"",r),n.has(o))throw new Error("Ordered maps must not include duplicate keys");n.set(o,a)}return n}static from(t,r,n){let i=BC.createPairs(t,r,n),o=new this;return o.items=i.items,o}};$a.tag="tag:yaml.org,2002:omap";var xM={collection:"seq",identify:e=>e instanceof Map,nodeClass:$a,default:!1,tag:"tag:yaml.org,2002:omap",resolve(e,t){let r=BC.resolvePairs(e,t),n=[];for(let{key:i}of r.items)DC.isScalar(i)&&(n.includes(i.value)?t(`Ordered maps must not include duplicate keys: ${i.value}`):n.push(i.value));return Object.assign(new $a,r)},createNode:(e,t,r)=>$a.from(e,t,r)};Kw.YAMLOMap=$a;Kw.omap=xM});var MC=$(Yw=>{"use strict";var WC=jt();function qC({value:e,source:t},r){return t&&(e?LC:VC).test.test(t)?t:e?r.options.trueStr:r.options.falseStr}var LC={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 WC.Scalar(!0),stringify:qC},VC={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 WC.Scalar(!1),stringify:qC};Yw.falseTag=VC;Yw.trueTag=LC});var FC=$(Op=>{"use strict";var PM=jt(),Xw=sc(),TM={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:Xw.stringifyNumber},OM={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():Xw.stringifyNumber(e)}},jM={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 PM.Scalar(parseFloat(e.replace(/_/g,""))),r=e.indexOf(".");if(r!==-1){let n=e.substring(r+1).replace(/_/g,"");n[n.length-1]==="0"&&(t.minFractionDigits=n.length)}return t},stringify:Xw.stringifyNumber};Op.float=jM;Op.floatExp=OM;Op.floatNaN=TM});var QC=$(lu=>{"use strict";var HC=sc(),cu=e=>typeof e=="bigint"||Number.isInteger(e);function jp(e,t,r,{intAsBigInt:n}){let i=e[0];if((i==="-"||i==="+")&&(t+=1),e=e.substring(t).replace(/_/g,""),n){switch(r){case 2:e=`0b${e}`;break;case 8:e=`0o${e}`;break;case 16:e=`0x${e}`;break}let a=BigInt(e);return i==="-"?BigInt(-1)*a:a}let o=parseInt(e,r);return i==="-"?-1*o:o}function Zw(e,t,r){let{value:n}=e;if(cu(n)){let i=n.toString(t);return n<0?"-"+r+i.substr(1):r+i}return HC.stringifyNumber(e)}var $M={identify:cu,default:!0,tag:"tag:yaml.org,2002:int",format:"BIN",test:/^[-+]?0b[0-1_]+$/,resolve:(e,t,r)=>jp(e,2,2,r),stringify:e=>Zw(e,2,"0b")},DM={identify:cu,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^[-+]?0[0-7_]+$/,resolve:(e,t,r)=>jp(e,1,8,r),stringify:e=>Zw(e,8,"0")},BM={identify:cu,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9][0-9_]*$/,resolve:(e,t,r)=>jp(e,0,10,r),stringify:HC.stringifyNumber},WM={identify:cu,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^[-+]?0x[0-9a-fA-F_]+$/,resolve:(e,t,r)=>jp(e,2,16,r),stringify:e=>Zw(e,16,"0x")};lu.int=BM;lu.intBin=$M;lu.intHex=WM;lu.intOct=DM});var ty=$(ey=>{"use strict";var Bp=De(),$p=Oo(),Dp=$o(),Da=class e extends Dp.YAMLMap{constructor(t){super(t),this.tag=e.tag}add(t){let r;Bp.isPair(t)?r=t:t&&typeof t=="object"&&"key"in t&&"value"in t&&t.value===null?r=new $p.Pair(t.key,null):r=new $p.Pair(t,null),Dp.findPair(this.items,r.key)||this.items.push(r)}get(t,r){let n=Dp.findPair(this.items,t);return!r&&Bp.isPair(n)?Bp.isScalar(n.key)?n.key.value:n.key:n}set(t,r){if(typeof r!="boolean")throw new Error(`Expected boolean value for set(key, value) in a YAML set, not ${typeof r}`);let n=Dp.findPair(this.items,t);n&&!r?this.items.splice(this.items.indexOf(n),1):!n&&r&&this.items.push(new $p.Pair(t))}toJSON(t,r){return super.toJSON(t,r,Set)}toString(t,r,n){if(!t)return JSON.stringify(this);if(this.hasAllNullValues(!0))return super.toString(Object.assign({},t,{allNullValues:!0}),r,n);throw new Error("Set items must all have null values")}static from(t,r,n){let{replacer:i}=n,o=new this(t);if(r&&Symbol.iterator in Object(r))for(let a of r)typeof i=="function"&&(a=i.call(r,a,a)),o.items.push($p.createPair(a,null,n));return o}};Da.tag="tag:yaml.org,2002:set";var qM={collection:"map",identify:e=>e instanceof Set,nodeClass:Da,default:!1,tag:"tag:yaml.org,2002:set",createNode:(e,t,r)=>Da.from(e,t,r),resolve(e,t){if(Bp.isMap(e)){if(e.hasAllNullValues(!0))return Object.assign(new Da,e);t("Set items must all have null values")}else t("Expected a mapping for this tag");return e}};ey.YAMLSet=Da;ey.set=qM});var ny=$(Wp=>{"use strict";var LM=sc();function ry(e,t){let r=e[0],n=r==="-"||r==="+"?e.substring(1):e,i=a=>t?BigInt(a):Number(a),o=n.replace(/_/g,"").split(":").reduce((a,s)=>a*i(60)+i(s),i(0));return r==="-"?i(-1)*o:o}function UC(e){let{value:t}=e,r=a=>a;if(typeof t=="bigint")r=a=>BigInt(a);else if(isNaN(t)||!isFinite(t))return LM.stringifyNumber(e);let n="";t<0&&(n="-",t*=r(-1));let i=r(60),o=[t%i];return t<60?o.unshift(0):(t=(t-o[0])/i,o.unshift(t%i),t>=60&&(t=(t-o[0])/i,o.unshift(t))),n+o.map(a=>String(a).padStart(2,"0")).join(":").replace(/000000\d*$/,"")}var VM={identify:e=>typeof e=="bigint"||Number.isInteger(e),default:!0,tag:"tag:yaml.org,2002:int",format:"TIME",test:/^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+$/,resolve:(e,t,{intAsBigInt:r})=>ry(e,r),stringify:UC},MM={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=>ry(e,!1),stringify:UC},JC={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(JC.test);if(!t)throw new Error("!!timestamp expects a date, starting with yyyy-mm-dd");let[,r,n,i,o,a,s]=t.map(Number),c=t[7]?Number((t[7]+"00").substr(1,3)):0,l=Date.UTC(r,n-1,i,o||0,a||0,s||0,c),u=t[8];if(u&&u!=="Z"){let f=ry(u,!1);Math.abs(f)<30&&(f*=60),l-=6e4*f}return new Date(l)},stringify:({value:e})=>e?.toISOString().replace(/(T00:00:00)?\.000Z$/,"")??""};Wp.floatTime=MM;Wp.intTime=VM;Wp.timestamp=JC});var GC=$(KC=>{"use strict";var FM=oc(),HM=Sp(),QM=ac(),UM=ou(),JM=Uw(),zC=MC(),iy=FC(),qp=QC(),zM=vp(),KM=Gw(),GM=Tp(),YM=ty(),oy=ny(),XM=[FM.map,QM.seq,UM.string,HM.nullTag,zC.trueTag,zC.falseTag,qp.intBin,qp.intOct,qp.int,qp.intHex,iy.floatNaN,iy.floatExp,iy.float,JM.binary,zM.merge,KM.omap,GM.pairs,YM.set,oy.intTime,oy.floatTime,oy.timestamp];KC.schema=XM});var a_=$(cy=>{"use strict";var e_=oc(),ZM=Sp(),t_=ac(),e1=ou(),t1=Ww(),ay=Lw(),sy=Mw(),r1=IC(),n1=TC(),r_=Uw(),uu=vp(),n_=Gw(),i_=Tp(),YC=GC(),o_=ty(),Lp=ny(),XC=new Map([["core",r1.schema],["failsafe",[e_.map,t_.seq,e1.string]],["json",n1.schema],["yaml11",YC.schema],["yaml-1.1",YC.schema]]),ZC={binary:r_.binary,bool:t1.boolTag,float:ay.float,floatExp:ay.floatExp,floatNaN:ay.floatNaN,floatTime:Lp.floatTime,int:sy.int,intHex:sy.intHex,intOct:sy.intOct,intTime:Lp.intTime,map:e_.map,merge:uu.merge,null:ZM.nullTag,omap:n_.omap,pairs:i_.pairs,seq:t_.seq,set:o_.set,timestamp:Lp.timestamp},i1={"tag:yaml.org,2002:binary":r_.binary,"tag:yaml.org,2002:merge":uu.merge,"tag:yaml.org,2002:omap":n_.omap,"tag:yaml.org,2002:pairs":i_.pairs,"tag:yaml.org,2002:set":o_.set,"tag:yaml.org,2002:timestamp":Lp.timestamp};function o1(e,t,r){let n=XC.get(t);if(n&&!e)return r&&!n.includes(uu.merge)?n.concat(uu.merge):n.slice();let i=n;if(!i)if(Array.isArray(e))i=[];else{let o=Array.from(XC.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 r&&(i=i.concat(uu.merge)),i.reduce((o,a)=>{let s=typeof a=="string"?ZC[a]:a;if(!s){let c=JSON.stringify(a),l=Object.keys(ZC).map(u=>JSON.stringify(u)).join(", ");throw new Error(`Unknown custom tag ${c}; use one of ${l}`)}return o.includes(s)||o.push(s),o},[])}cy.coreKnownTags=i1;cy.getTags=o1});var dy=$(s_=>{"use strict";var ly=De(),a1=oc(),s1=ac(),c1=ou(),Vp=a_(),l1=(e,t)=>e.key<t.key?-1:e.key>t.key?1:0,uy=class e{constructor({compat:t,customTags:r,merge:n,resolveKnownTags:i,schema:o,sortMapEntries:a,toStringDefaults:s}){this.compat=Array.isArray(t)?Vp.getTags(t,"compat"):t?Vp.getTags(null,t):null,this.name=typeof o=="string"&&o||"core",this.knownTags=i?Vp.coreKnownTags:{},this.tags=Vp.getTags(r,this.name,n),this.toStringOptions=s??null,Object.defineProperty(this,ly.MAP,{value:a1.map}),Object.defineProperty(this,ly.SCALAR,{value:c1.string}),Object.defineProperty(this,ly.SEQ,{value:s1.seq}),this.sortMapEntries=typeof a=="function"?a:a===!0?l1:null}clone(){let t=Object.create(e.prototype,Object.getOwnPropertyDescriptors(this));return t.tags=this.tags.slice(),t}};s_.Schema=uy});var l_=$(c_=>{"use strict";var u1=De(),fy=ru(),du=Xl();function d1(e,t){let r=[],n=t.directives===!0;if(t.directives!==!1&&e.directives){let c=e.directives.toString(e);c?(r.push(c),n=!0):e.directives.docStart&&(n=!0)}n&&r.push("---");let i=fy.createStringifyContext(e,t),{commentString:o}=i.options;if(e.commentBefore){r.length!==1&&r.unshift("");let c=o(e.commentBefore);r.unshift(du.indentComment(c,""))}let a=!1,s=null;if(e.contents){if(u1.isNode(e.contents)){if(e.contents.spaceBefore&&n&&r.push(""),e.contents.commentBefore){let u=o(e.contents.commentBefore);r.push(du.indentComment(u,""))}i.forceBlockIndent=!!e.comment,s=e.contents.comment}let c=s?void 0:()=>a=!0,l=fy.stringify(e.contents,i,()=>s=null,c);s&&(l+=du.lineComment(l,"",o(s))),(l[0]==="|"||l[0]===">")&&r[r.length-1]==="---"?r[r.length-1]=`--- ${l}`:r.push(l)}else r.push(fy.stringify(e.contents,i));if(e.directives?.docEnd)if(e.comment){let c=o(e.comment);c.includes(`
|
|
58
|
+
`)?(r.push("..."),r.push(du.indentComment(c,""))):r.push(`... ${c}`)}else r.push("...");else{let c=e.comment;c&&a&&(c=c.replace(/^\n+/,"")),c&&((!a||s)&&r[r.length-1]!==""&&r.push(""),r.push(du.indentComment(o(c),"")))}return r.join(`
|
|
59
|
+
`)+`
|
|
60
|
+
`}c_.stringifyDocument=d1});var fu=$(u_=>{"use strict";var f1=Gl(),cc=sp(),Sn=De(),p1=Oo(),m1=Io(),h1=dy(),g1=l_(),py=np(),v1=vw(),w1=Yl(),my=gw(),hy=class e{constructor(t,r,n){this.commentBefore=null,this.comment=null,this.errors=[],this.warnings=[],Object.defineProperty(this,Sn.NODE_TYPE,{value:Sn.DOC});let i=null;typeof r=="function"||Array.isArray(r)?i=r:n===void 0&&r&&(n=r,r=void 0);let o=Object.assign({intAsBigInt:!1,keepSourceTokens:!1,logLevel:"warn",prettyErrors:!0,strict:!0,stringKeys:!1,uniqueKeys:!0,version:"1.2"},n);this.options=o;let{version:a}=o;n?._directives?(this.directives=n._directives.atDocument(),this.directives.yaml.explicit&&(a=this.directives.yaml.version)):this.directives=new my.Directives({version:a}),this.setSchema(a,n),this.contents=t===void 0?null:this.createNode(t,i,n)}clone(){let t=Object.create(e.prototype,{[Sn.NODE_TYPE]:{value:Sn.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=Sn.isNode(this.contents)?this.contents.clone(t.schema):this.contents,this.range&&(t.range=this.range.slice()),t}add(t){lc(this.contents)&&this.contents.add(t)}addIn(t,r){lc(this.contents)&&this.contents.addIn(t,r)}createAlias(t,r){if(!t.anchor){let n=py.anchorNames(this);t.anchor=!r||n.has(r)?py.findNewAnchor(r||"a",n):r}return new f1.Alias(t.anchor)}createNode(t,r,n){let i;if(typeof r=="function")t=r.call({"":t},"",t),i=r;else if(Array.isArray(r)){let g=w=>typeof w=="number"||w instanceof String||w instanceof Number,v=r.filter(g).map(String);v.length>0&&(r=r.concat(v)),i=r}else n===void 0&&r&&(n=r,r=void 0);let{aliasDuplicateObjects:o,anchorPrefix:a,flow:s,keepUndefined:c,onTagObj:l,tag:u}=n??{},{onAnchor:f,setAnchors:d,sourceObjects:p}=py.createNodeAnchors(this,a||"a"),m={aliasDuplicateObjects:o??!0,keepUndefined:c??!1,onAnchor:f,onTagObj:l,replacer:i,schema:this.schema,sourceObjects:p},h=w1.createNode(t,u,m);return s&&Sn.isCollection(h)&&(h.flow=!0),d(),h}createPair(t,r,n={}){let i=this.createNode(t,null,n),o=this.createNode(r,null,n);return new p1.Pair(i,o)}delete(t){return lc(this.contents)?this.contents.delete(t):!1}deleteIn(t){return cc.isEmptyPath(t)?this.contents==null?!1:(this.contents=null,!0):lc(this.contents)?this.contents.deleteIn(t):!1}get(t,r){return Sn.isCollection(this.contents)?this.contents.get(t,r):void 0}getIn(t,r){return cc.isEmptyPath(t)?!r&&Sn.isScalar(this.contents)?this.contents.value:this.contents:Sn.isCollection(this.contents)?this.contents.getIn(t,r):void 0}has(t){return Sn.isCollection(this.contents)?this.contents.has(t):!1}hasIn(t){return cc.isEmptyPath(t)?this.contents!==void 0:Sn.isCollection(this.contents)?this.contents.hasIn(t):!1}set(t,r){this.contents==null?this.contents=cc.collectionFromPath(this.schema,[t],r):lc(this.contents)&&this.contents.set(t,r)}setIn(t,r){cc.isEmptyPath(t)?this.contents=r:this.contents==null?this.contents=cc.collectionFromPath(this.schema,Array.from(t),r):lc(this.contents)&&this.contents.setIn(t,r)}setSchema(t,r={}){typeof t=="number"&&(t=String(t));let n;switch(t){case"1.1":this.directives?this.directives.yaml.version="1.1":this.directives=new my.Directives({version:"1.1"}),n={resolveKnownTags:!1,schema:"yaml-1.1"};break;case"1.2":case"next":this.directives?this.directives.yaml.version=t:this.directives=new my.Directives({version:t}),n={resolveKnownTags:!0,schema:"core"};break;case null:this.directives&&delete this.directives,n=null;break;default:{let i=JSON.stringify(t);throw new Error(`Expected '1.1', '1.2' or null as first argument, but found: ${i}`)}}if(r.schema instanceof Object)this.schema=r.schema;else if(n)this.schema=new h1.Schema(Object.assign(n,r));else throw new Error("With a null YAML version, the { schema: Schema } option is required")}toJS({json:t,jsonArg:r,mapAsMap:n,maxAliasCount:i,onAnchor:o,reviver:a}={}){let s={anchors:new Map,doc:this,keep:!t,mapAsMap:n===!0,mapKeyWarned:!1,maxAliasCount:typeof i=="number"?i:100},c=m1.toJS(this.contents,r??"",s);if(typeof o=="function")for(let{count:l,res:u}of s.anchors.values())o(u,l);return typeof a=="function"?v1.applyReviver(a,{"":c},"",c):c}toJSON(t,r){return this.toJS({json:!0,jsonArg:t,mapAsMap:!1,onAnchor:r})}toString(t={}){if(this.errors.length>0)throw new Error("Document with errors cannot be stringified");if("indent"in t&&(!Number.isInteger(t.indent)||Number(t.indent)<=0)){let r=JSON.stringify(t.indent);throw new Error(`"indent" option must be a positive integer, not ${r}`)}return g1.stringifyDocument(this,t)}};function lc(e){if(Sn.isCollection(e))return!0;throw new Error("Expected a YAML collection as document contents")}u_.Document=hy});var hu=$(mu=>{"use strict";var pu=class extends Error{constructor(t,r,n,i){super(),this.name=t,this.code=n,this.message=i,this.pos=r}},gy=class extends pu{constructor(t,r,n){super("YAMLParseError",t,r,n)}},vy=class extends pu{constructor(t,r,n){super("YAMLWarning",t,r,n)}},y1=(e,t)=>r=>{if(r.pos[0]===-1)return;r.linePos=r.pos.map(s=>t.linePos(s));let{line:n,col:i}=r.linePos[0];r.message+=` at line ${n}, column ${i}`;let o=i-1,a=e.substring(t.lineStarts[n-1],t.lineStarts[n]).replace(/[\n\r]+$/,"");if(o>=60&&a.length>80){let s=Math.min(o-39,a.length-79);a="…"+a.substring(s),o-=s-1}if(a.length>80&&(a=a.substring(0,79)+"…"),n>1&&/^ *$/.test(a.substring(0,o))){let s=e.substring(t.lineStarts[n-2],t.lineStarts[n-1]);s.length>80&&(s=s.substring(0,79)+`…
|
|
61
|
+
`),a=s+a}if(/[^ ]/.test(a)){let s=1,c=r.linePos[1];c?.line===n&&c.col>i&&(s=Math.max(1,Math.min(c.col-i,80-o)));let l=" ".repeat(o)+"^".repeat(s);r.message+=`:
|
|
62
|
+
|
|
63
|
+
${a}
|
|
64
|
+
${l}
|
|
65
|
+
`}};mu.YAMLError=pu;mu.YAMLParseError=gy;mu.YAMLWarning=vy;mu.prettifyError=y1});var gu=$(d_=>{"use strict";function k1(e,{flow:t,indicator:r,next:n,offset:i,onError:o,parentIndent:a,startOnNewline:s}){let c=!1,l=s,u=s,f="",d="",p=!1,m=!1,h=null,g=null,v=null,w=null,y=null,R=null,N=null;for(let I of e)switch(m&&(I.type!=="space"&&I.type!=="newline"&&I.type!=="comma"&&o(I.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space"),m=!1),h&&(l&&I.type!=="comment"&&I.type!=="newline"&&o(h,"TAB_AS_INDENT","Tabs are not allowed as indentation"),h=null),I.type){case"space":!t&&(r!=="doc-start"||n?.type!=="flow-collection")&&I.source.includes(" ")&&(h=I),u=!0;break;case"comment":{u||o(I,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");let W=I.source.substring(1)||" ";f?f+=d+W:f=W,d="",l=!1;break}case"newline":l?f?f+=I.source:(!R||r!=="seq-item-ind")&&(c=!0):d+=I.source,l=!0,p=!0,(g||v)&&(w=I),u=!0;break;case"anchor":g&&o(I,"MULTIPLE_ANCHORS","A node can have at most one anchor"),I.source.endsWith(":")&&o(I.offset+I.source.length-1,"BAD_ALIAS","Anchor ending in : is ambiguous",!0),g=I,N??(N=I.offset),l=!1,u=!1,m=!0;break;case"tag":{v&&o(I,"MULTIPLE_TAGS","A node can have at most one tag"),v=I,N??(N=I.offset),l=!1,u=!1,m=!0;break}case r:(g||v)&&o(I,"BAD_PROP_ORDER",`Anchors and tags must be after the ${I.source} indicator`),R&&o(I,"UNEXPECTED_TOKEN",`Unexpected ${I.source} in ${t??"collection"}`),R=I,l=r==="seq-item-ind"||r==="explicit-key-ind",u=!1;break;case"comma":if(t){y&&o(I,"UNEXPECTED_TOKEN",`Unexpected , in ${t}`),y=I,l=!1,u=!1;break}default:o(I,"UNEXPECTED_TOKEN",`Unexpected ${I.type} token`),l=!1,u=!1}let b=e[e.length-1],E=b?b.offset+b.source.length:i;return m&&n&&n.type!=="space"&&n.type!=="newline"&&n.type!=="comma"&&(n.type!=="scalar"||n.source!=="")&&o(n.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space"),h&&(l&&h.indent<=a||n?.type==="block-map"||n?.type==="block-seq")&&o(h,"TAB_AS_INDENT","Tabs are not allowed as indentation"),{comma:y,found:R,spaceBefore:c,comment:f,hasNewline:p,anchor:g,tag:v,newlineAfterProp:w,end:E,start:N??E}}d_.resolveProps=k1});var Mp=$(f_=>{"use strict";function wy(e){if(!e)return null;switch(e.type){case"alias":case"scalar":case"double-quoted-scalar":case"single-quoted-scalar":if(e.source.includes(`
|
|
66
|
+
`))return!0;if(e.end){for(let t of e.end)if(t.type==="newline")return!0}return!1;case"flow-collection":for(let t of e.items){for(let r of t.start)if(r.type==="newline")return!0;if(t.sep){for(let r of t.sep)if(r.type==="newline")return!0}if(wy(t.key)||wy(t.value))return!0}return!1;default:return!0}}f_.containsNewline=wy});var yy=$(p_=>{"use strict";var b1=Mp();function A1(e,t,r){if(t?.type==="flow-collection"){let n=t.end[0];n.indent===e&&(n.source==="]"||n.source==="}")&&b1.containsNewline(t)&&r(n,"BAD_INDENT","Flow end indicator should be more indented than parent",!0)}}p_.flowIndentCheck=A1});var ky=$(h_=>{"use strict";var m_=De();function R1(e,t,r){let{uniqueKeys:n}=e.options;if(n===!1)return!1;let i=typeof n=="function"?n:(o,a)=>o===a||m_.isScalar(o)&&m_.isScalar(a)&&o.value===a.value;return t.some(o=>i(o.key,r))}h_.mapIncludes=R1});var b_=$(k_=>{"use strict";var g_=Oo(),N1=$o(),v_=gu(),S1=Mp(),w_=yy(),E1=ky(),y_="All mapping items must start at the same column";function C1({composeNode:e,composeEmptyNode:t},r,n,i,o){let a=o?.nodeClass??N1.YAMLMap,s=new a(r.schema);r.atRoot&&(r.atRoot=!1);let c=n.offset,l=null;for(let u of n.items){let{start:f,key:d,sep:p,value:m}=u,h=v_.resolveProps(f,{indicator:"explicit-key-ind",next:d??p?.[0],offset:c,onError:i,parentIndent:n.indent,startOnNewline:!0}),g=!h.found;if(g){if(d&&(d.type==="block-seq"?i(c,"BLOCK_AS_IMPLICIT_KEY","A block sequence may not be used as an implicit map key"):"indent"in d&&d.indent!==n.indent&&i(c,"BAD_INDENT",y_)),!h.anchor&&!h.tag&&!p){l=h.end,h.comment&&(s.comment?s.comment+=`
|
|
67
|
+
`+h.comment:s.comment=h.comment);continue}(h.newlineAfterProp||S1.containsNewline(d))&&i(d??f[f.length-1],"MULTILINE_IMPLICIT_KEY","Implicit keys need to be on a single line")}else h.found?.indent!==n.indent&&i(c,"BAD_INDENT",y_);r.atKey=!0;let v=h.end,w=d?e(r,d,h,i):t(r,v,f,null,h,i);r.schema.compat&&w_.flowIndentCheck(n.indent,d,i),r.atKey=!1,E1.mapIncludes(r,s.items,w)&&i(v,"DUPLICATE_KEY","Map keys must be unique");let y=v_.resolveProps(p??[],{indicator:"map-value-ind",next:m,offset:w.range[2],onError:i,parentIndent:n.indent,startOnNewline:!d||d.type==="block-scalar"});if(c=y.end,y.found){g&&(m?.type==="block-map"&&!y.hasNewline&&i(c,"BLOCK_AS_IMPLICIT_KEY","Nested mappings are not allowed in compact mappings"),r.options.strict&&h.start<y.found.offset-1024&&i(w.range,"KEY_OVER_1024_CHARS","The : indicator must be at most 1024 chars after the start of an implicit block mapping key"));let R=m?e(r,m,y,i):t(r,c,p,null,y,i);r.schema.compat&&w_.flowIndentCheck(n.indent,m,i),c=R.range[2];let N=new g_.Pair(w,R);r.options.keepSourceTokens&&(N.srcToken=u),s.items.push(N)}else{g&&i(w.range,"MISSING_CHAR","Implicit map keys need to be followed by map values"),y.comment&&(w.comment?w.comment+=`
|
|
68
|
+
`+y.comment:w.comment=y.comment);let R=new g_.Pair(w);r.options.keepSourceTokens&&(R.srcToken=u),s.items.push(R)}}return l&&l<c&&i(l,"IMPOSSIBLE","Map comment with trailing content"),s.range=[n.offset,c,l??c],s}k_.resolveBlockMap=C1});var R_=$(A_=>{"use strict";var _1=Do(),I1=gu(),x1=yy();function P1({composeNode:e,composeEmptyNode:t},r,n,i,o){let a=o?.nodeClass??_1.YAMLSeq,s=new a(r.schema);r.atRoot&&(r.atRoot=!1),r.atKey&&(r.atKey=!1);let c=n.offset,l=null;for(let{start:u,value:f}of n.items){let d=I1.resolveProps(u,{indicator:"seq-item-ind",next:f,offset:c,onError:i,parentIndent:n.indent,startOnNewline:!0});if(!d.found)if(d.anchor||d.tag||f)f?.type==="block-seq"?i(d.end,"BAD_INDENT","All sequence items must start at the same column"):i(c,"MISSING_CHAR","Sequence item without - indicator");else{l=d.end,d.comment&&(s.comment=d.comment);continue}let p=f?e(r,f,d,i):t(r,d.end,u,null,d,i);r.schema.compat&&x1.flowIndentCheck(n.indent,f,i),c=p.range[2],s.items.push(p)}return s.range=[n.offset,c,l??c],s}A_.resolveBlockSeq=P1});var uc=$(N_=>{"use strict";function T1(e,t,r,n){let i="";if(e){let o=!1,a="";for(let s of e){let{source:c,type:l}=s;switch(l){case"space":o=!0;break;case"comment":{r&&!o&&n(s,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");let u=c.substring(1)||" ";i?i+=a+u:i=u,a="";break}case"newline":i&&(a+=c),o=!0;break;default:n(s,"UNEXPECTED_TOKEN",`Unexpected ${l} at node end`)}t+=c.length}}return{comment:i,offset:t}}N_.resolveEnd=T1});var __=$(C_=>{"use strict";var O1=De(),j1=Oo(),S_=$o(),$1=Do(),D1=uc(),E_=gu(),B1=Mp(),W1=ky(),by="Block collections are not allowed within flow collections",Ay=e=>e&&(e.type==="block-map"||e.type==="block-seq");function q1({composeNode:e,composeEmptyNode:t},r,n,i,o){let a=n.start.source==="{",s=a?"flow map":"flow sequence",c=o?.nodeClass??(a?S_.YAMLMap:$1.YAMLSeq),l=new c(r.schema);l.flow=!0;let u=r.atRoot;u&&(r.atRoot=!1),r.atKey&&(r.atKey=!1);let f=n.offset+n.start.source.length;for(let g=0;g<n.items.length;++g){let v=n.items[g],{start:w,key:y,sep:R,value:N}=v,b=E_.resolveProps(w,{flow:s,indicator:"explicit-key-ind",next:y??R?.[0],offset:f,onError:i,parentIndent:n.indent,startOnNewline:!1});if(!b.found){if(!b.anchor&&!b.tag&&!R&&!N){g===0&&b.comma?i(b.comma,"UNEXPECTED_TOKEN",`Unexpected , in ${s}`):g<n.items.length-1&&i(b.start,"UNEXPECTED_TOKEN",`Unexpected empty item in ${s}`),b.comment&&(l.comment?l.comment+=`
|
|
69
|
+
`+b.comment:l.comment=b.comment),f=b.end;continue}!a&&r.options.strict&&B1.containsNewline(y)&&i(y,"MULTILINE_IMPLICIT_KEY","Implicit keys of flow sequence pairs need to be on a single line")}if(g===0)b.comma&&i(b.comma,"UNEXPECTED_TOKEN",`Unexpected , in ${s}`);else if(b.comma||i(b.start,"MISSING_CHAR",`Missing , between ${s} items`),b.comment){let E="";e:for(let I of w)switch(I.type){case"comma":case"space":break;case"comment":E=I.source.substring(1);break e;default:break e}if(E){let I=l.items[l.items.length-1];O1.isPair(I)&&(I=I.value??I.key),I.comment?I.comment+=`
|
|
70
|
+
`+E:I.comment=E,b.comment=b.comment.substring(E.length+1)}}if(!a&&!R&&!b.found){let E=N?e(r,N,b,i):t(r,b.end,R,null,b,i);l.items.push(E),f=E.range[2],Ay(N)&&i(E.range,"BLOCK_IN_FLOW",by)}else{r.atKey=!0;let E=b.end,I=y?e(r,y,b,i):t(r,E,w,null,b,i);Ay(y)&&i(I.range,"BLOCK_IN_FLOW",by),r.atKey=!1;let W=E_.resolveProps(R??[],{flow:s,indicator:"map-value-ind",next:N,offset:I.range[2],onError:i,parentIndent:n.indent,startOnNewline:!1});if(W.found){if(!a&&!b.found&&r.options.strict){if(R)for(let Z of R){if(Z===W.found)break;if(Z.type==="newline"){i(Z,"MULTILINE_IMPLICIT_KEY","Implicit keys of flow sequence pairs need to be on a single line");break}}b.start<W.found.offset-1024&&i(W.found,"KEY_OVER_1024_CHARS","The : indicator must be at most 1024 chars after the start of an implicit flow sequence key")}}else N&&("source"in N&&N.source?.[0]===":"?i(N,"MISSING_CHAR",`Missing space after : in ${s}`):i(W.start,"MISSING_CHAR",`Missing , or : between ${s} items`));let F=N?e(r,N,W,i):W.found?t(r,W.end,R,null,W,i):null;F?Ay(N)&&i(F.range,"BLOCK_IN_FLOW",by):W.comment&&(I.comment?I.comment+=`
|
|
71
|
+
`+W.comment:I.comment=W.comment);let G=new j1.Pair(I,F);if(r.options.keepSourceTokens&&(G.srcToken=v),a){let Z=l;W1.mapIncludes(r,Z.items,I)&&i(E,"DUPLICATE_KEY","Map keys must be unique"),Z.items.push(G)}else{let Z=new S_.YAMLMap(r.schema);Z.flow=!0,Z.items.push(G);let Ae=(F??I).range;Z.range=[I.range[0],Ae[1],Ae[2]],l.items.push(Z)}f=F?F.range[2]:W.end}}let d=a?"}":"]",[p,...m]=n.end,h=f;if(p?.source===d)h=p.offset+p.source.length;else{let g=s[0].toUpperCase()+s.substring(1),v=u?`${g} must end with a ${d}`:`${g} in block collection must be sufficiently indented and end with a ${d}`;i(f,u?"MISSING_CHAR":"BAD_INDENT",v),p&&p.source.length!==1&&m.unshift(p)}if(m.length>0){let g=D1.resolveEnd(m,h,r.options.strict,i);g.comment&&(l.comment?l.comment+=`
|
|
72
|
+
`+g.comment:l.comment=g.comment),l.range=[n.offset,h,g.offset]}else l.range=[n.offset,h,h];return l}C_.resolveFlowCollection=q1});var x_=$(I_=>{"use strict";var L1=De(),V1=jt(),M1=$o(),F1=Do(),H1=b_(),Q1=R_(),U1=__();function Ry(e,t,r,n,i,o){let a=r.type==="block-map"?H1.resolveBlockMap(e,t,r,n,o):r.type==="block-seq"?Q1.resolveBlockSeq(e,t,r,n,o):U1.resolveFlowCollection(e,t,r,n,o),s=a.constructor;return i==="!"||i===s.tagName?(a.tag=s.tagName,a):(i&&(a.tag=i),a)}function J1(e,t,r,n,i){let o=n.tag,a=o?t.directives.tagName(o.source,d=>i(o,"TAG_RESOLVE_FAILED",d)):null;if(r.type==="block-seq"){let{anchor:d,newlineAfterProp:p}=n,m=d&&o?d.offset>o.offset?d:o:d??o;m&&(!p||p.offset<m.offset)&&i(m,"MISSING_CHAR","Missing newline after block sequence props")}let s=r.type==="block-map"?"map":r.type==="block-seq"?"seq":r.start.source==="{"?"map":"seq";if(!o||!a||a==="!"||a===M1.YAMLMap.tagName&&s==="map"||a===F1.YAMLSeq.tagName&&s==="seq")return Ry(e,t,r,i,a);let c=t.schema.tags.find(d=>d.tag===a&&d.collection===s);if(!c){let d=t.schema.knownTags[a];if(d?.collection===s)t.schema.tags.push(Object.assign({},d,{default:!1})),c=d;else return d?i(o,"BAD_COLLECTION_TYPE",`${d.tag} used for ${s} collection, but expects ${d.collection??"scalar"}`,!0):i(o,"TAG_RESOLVE_FAILED",`Unresolved tag: ${a}`,!0),Ry(e,t,r,i,a)}let l=Ry(e,t,r,i,a,c),u=c.resolve?.(l,d=>i(o,"TAG_RESOLVE_FAILED",d),t.options)??l,f=L1.isNode(u)?u:new V1.Scalar(u);return f.range=l.range,f.tag=a,c?.format&&(f.format=c.format),f}I_.composeCollection=J1});var Sy=$(P_=>{"use strict";var Ny=jt();function z1(e,t,r){let n=t.offset,i=K1(t,e.options.strict,r);if(!i)return{value:"",type:null,comment:"",range:[n,n,n]};let o=i.mode===">"?Ny.Scalar.BLOCK_FOLDED:Ny.Scalar.BLOCK_LITERAL,a=t.source?G1(t.source):[],s=a.length;for(let h=a.length-1;h>=0;--h){let g=a[h][1];if(g===""||g==="\r")s=h;else break}if(s===0){let h=i.chomp==="+"&&a.length>0?`
|
|
73
|
+
`.repeat(Math.max(1,a.length-1)):"",g=n+i.length;return t.source&&(g+=t.source.length),{value:h,type:o,comment:i.comment,range:[n,g,g]}}let c=t.indent+i.indent,l=t.offset+i.length,u=0;for(let h=0;h<s;++h){let[g,v]=a[h];if(v===""||v==="\r")i.indent===0&&g.length>c&&(c=g.length);else{g.length<c&&r(l+g.length,"MISSING_CHAR","Block scalars with more-indented leading empty lines must use an explicit indentation indicator"),i.indent===0&&(c=g.length),u=h,c===0&&!e.atRoot&&r(l,"BAD_INDENT","Block scalar values in collections must be indented");break}l+=g.length+v.length+1}for(let h=a.length-1;h>=s;--h)a[h][0].length>c&&(s=h+1);let f="",d="",p=!1;for(let h=0;h<u;++h)f+=a[h][0].slice(c)+`
|
|
74
|
+
`;for(let h=u;h<s;++h){let[g,v]=a[h];l+=g.length+v.length+1;let w=v[v.length-1]==="\r";if(w&&(v=v.slice(0,-1)),v&&g.length<c){let R=`Block scalar lines must not be less indented than their ${i.indent?"explicit indentation indicator":"first line"}`;r(l-v.length-(w?2:1),"BAD_INDENT",R),g=""}o===Ny.Scalar.BLOCK_LITERAL?(f+=d+g.slice(c)+v,d=`
|
|
75
|
+
`):g.length>c||v[0]===" "?(d===" "?d=`
|
|
76
|
+
`:!p&&d===`
|
|
77
|
+
`&&(d=`
|
|
78
|
+
|
|
79
|
+
`),f+=d+g.slice(c)+v,d=`
|
|
80
|
+
`,p=!0):v===""?d===`
|
|
81
|
+
`?f+=`
|
|
82
|
+
`:d=`
|
|
83
|
+
`:(f+=d+v,d=" ",p=!1)}switch(i.chomp){case"-":break;case"+":for(let h=s;h<a.length;++h)f+=`
|
|
84
|
+
`+a[h][0].slice(c);f[f.length-1]!==`
|
|
85
|
+
`&&(f+=`
|
|
86
|
+
`);break;default:f+=`
|
|
87
|
+
`}let m=n+i.length+t.source.length;return{value:f,type:o,comment:i.comment,range:[n,m,m]}}function K1({offset:e,props:t},r,n){if(t[0].type!=="block-scalar-header")return n(t[0],"IMPOSSIBLE","Block scalar header not found"),null;let{source:i}=t[0],o=i[0],a=0,s="",c=-1;for(let d=1;d<i.length;++d){let p=i[d];if(!s&&(p==="-"||p==="+"))s=p;else{let m=Number(p);!a&&m?a=m:c===-1&&(c=e+d)}}c!==-1&&n(c,"UNEXPECTED_TOKEN",`Block scalar header includes extra characters: ${i}`);let l=!1,u="",f=i.length;for(let d=1;d<t.length;++d){let p=t[d];switch(p.type){case"space":l=!0;case"newline":f+=p.source.length;break;case"comment":r&&!l&&n(p,"MISSING_CHAR","Comments must be separated from other tokens by white space characters"),f+=p.source.length,u=p.source.substring(1);break;case"error":n(p,"UNEXPECTED_TOKEN",p.message),f+=p.source.length;break;default:{let m=`Unexpected token in block scalar header: ${p.type}`;n(p,"UNEXPECTED_TOKEN",m);let h=p.source;h&&typeof h=="string"&&(f+=h.length)}}}return{mode:o,indent:a,chomp:s,comment:u,length:f}}function G1(e){let t=e.split(/\n( *)/),r=t[0],n=r.match(/^( *)/),o=[n?.[1]?[n[1],r.slice(n[1].length)]:["",r]];for(let a=1;a<t.length;a+=2)o.push([t[a],t[a+1]]);return o}P_.resolveBlockScalar=z1});var Cy=$(O_=>{"use strict";var Ey=jt(),Y1=uc();function X1(e,t,r){let{offset:n,type:i,source:o,end:a}=e,s,c,l=(d,p,m)=>r(n+d,p,m);switch(i){case"scalar":s=Ey.Scalar.PLAIN,c=Z1(o,l);break;case"single-quoted-scalar":s=Ey.Scalar.QUOTE_SINGLE,c=eF(o,l);break;case"double-quoted-scalar":s=Ey.Scalar.QUOTE_DOUBLE,c=tF(o,l);break;default:return r(e,"UNEXPECTED_TOKEN",`Expected a flow scalar value, but found: ${i}`),{value:"",type:null,comment:"",range:[n,n+o.length,n+o.length]}}let u=n+o.length,f=Y1.resolveEnd(a,u,t,r);return{value:c,type:s,comment:f.comment,range:[n,u,f.offset]}}function Z1(e,t){let r="";switch(e[0]){case" ":r="a tab character";break;case",":r="flow indicator character ,";break;case"%":r="directive indicator character %";break;case"|":case">":{r=`block scalar indicator ${e[0]}`;break}case"@":case"`":{r=`reserved character ${e[0]}`;break}}return r&&t(0,"BAD_SCALAR_START",`Plain value cannot start with ${r}`),T_(e)}function eF(e,t){return(e[e.length-1]!=="'"||e.length===1)&&t(e.length,"MISSING_CHAR","Missing closing 'quote"),T_(e.slice(1,-1)).replace(/''/g,"'")}function T_(e){let t,r;try{t=new RegExp(`(.*?)(?<![ ])[ ]*\r?
|
|
88
|
+
`,"sy"),r=new RegExp(`[ ]*(.*?)(?:(?<![ ])[ ]*)?\r?
|
|
89
|
+
`,"sy")}catch{t=/(.*?)[ \t]*\r?\n/sy,r=/[ \t]*(.*?)[ \t]*\r?\n/sy}let n=t.exec(e);if(!n)return e;let i=n[1],o=" ",a=t.lastIndex;for(r.lastIndex=a;n=r.exec(e);)n[1]===""?o===`
|
|
90
|
+
`?i+=o:o=`
|
|
91
|
+
`:(i+=o+n[1],o=" "),a=r.lastIndex;let s=/[ \t]*(.*)/sy;return s.lastIndex=a,n=s.exec(e),i+o+(n?.[1]??"")}function tF(e,t){let r="";for(let n=1;n<e.length-1;++n){let i=e[n];if(!(i==="\r"&&e[n+1]===`
|
|
92
|
+
`))if(i===`
|
|
93
|
+
`){let{fold:o,offset:a}=rF(e,n);r+=o,n=a}else if(i==="\\"){let o=e[++n],a=nF[o];if(a)r+=a;else if(o===`
|
|
94
|
+
`)for(o=e[n+1];o===" "||o===" ";)o=e[++n+1];else if(o==="\r"&&e[n+1]===`
|
|
95
|
+
`)for(o=e[++n+1];o===" "||o===" ";)o=e[++n+1];else if(o==="x"||o==="u"||o==="U"){let s=o==="x"?2:o==="u"?4:8;r+=iF(e,n+1,s,t),n+=s}else{let s=e.substr(n-1,2);t(n-1,"BAD_DQ_ESCAPE",`Invalid escape sequence ${s}`),r+=s}}else if(i===" "||i===" "){let o=n,a=e[n+1];for(;a===" "||a===" ";)a=e[++n+1];a!==`
|
|
96
|
+
`&&!(a==="\r"&&e[n+2]===`
|
|
97
|
+
`)&&(r+=n>o?e.slice(o,n+1):i)}else r+=i}return(e[e.length-1]!=='"'||e.length===1)&&t(e.length,"MISSING_CHAR",'Missing closing "quote'),r}function rF(e,t){let r="",n=e[t+1];for(;(n===" "||n===" "||n===`
|
|
98
|
+
`||n==="\r")&&!(n==="\r"&&e[t+2]!==`
|
|
99
|
+
`);)n===`
|
|
100
|
+
`&&(r+=`
|
|
101
|
+
`),t+=1,n=e[t+1];return r||(r=" "),{fold:r,offset:t}}var nF={0:"\0",a:"\x07",b:"\b",e:"\x1B",f:"\f",n:`
|
|
102
|
+
`,r:"\r",t:" ",v:"\v",N:"
",_:" ",L:"\u2028",P:"\u2029"," ":" ",'"':'"',"/":"/","\\":"\\"," ":" "};function iF(e,t,r,n){let i=e.substr(t,r),a=i.length===r&&/^[0-9a-fA-F]+$/.test(i)?parseInt(i,16):NaN;try{return String.fromCodePoint(a)}catch{let s=e.substr(t-2,r+2);return n(t-2,"BAD_DQ_ESCAPE",`Invalid escape sequence ${s}`),s}}O_.resolveFlowScalar=X1});var D_=$($_=>{"use strict";var Ba=De(),j_=jt(),oF=Sy(),aF=Cy();function sF(e,t,r,n){let{value:i,type:o,comment:a,range:s}=t.type==="block-scalar"?oF.resolveBlockScalar(e,t,n):aF.resolveFlowScalar(t,e.options.strict,n),c=r?e.directives.tagName(r.source,f=>n(r,"TAG_RESOLVE_FAILED",f)):null,l;e.options.stringKeys&&e.atKey?l=e.schema[Ba.SCALAR]:c?l=cF(e.schema,i,c,r,n):t.type==="scalar"?l=lF(e,i,t,n):l=e.schema[Ba.SCALAR];let u;try{let f=l.resolve(i,d=>n(r??t,"TAG_RESOLVE_FAILED",d),e.options);u=Ba.isScalar(f)?f:new j_.Scalar(f)}catch(f){let d=f instanceof Error?f.message:String(f);n(r??t,"TAG_RESOLVE_FAILED",d),u=new j_.Scalar(i)}return u.range=s,u.source=i,o&&(u.type=o),c&&(u.tag=c),l.format&&(u.format=l.format),a&&(u.comment=a),u}function cF(e,t,r,n,i){if(r==="!")return e[Ba.SCALAR];let o=[];for(let s of e.tags)if(!s.collection&&s.tag===r)if(s.default&&s.test)o.push(s);else return s;for(let s of o)if(s.test?.test(t))return s;let a=e.knownTags[r];return a&&!a.collection?(e.tags.push(Object.assign({},a,{default:!1,test:void 0})),a):(i(n,"TAG_RESOLVE_FAILED",`Unresolved tag: ${r}`,r!=="tag:yaml.org,2002:str"),e[Ba.SCALAR])}function lF({atKey:e,directives:t,schema:r},n,i,o){let a=r.tags.find(s=>(s.default===!0||e&&s.default==="key")&&s.test?.test(n))||r[Ba.SCALAR];if(r.compat){let s=r.compat.find(c=>c.default&&c.test?.test(n))??r[Ba.SCALAR];if(a.tag!==s.tag){let c=t.tagString(a.tag),l=t.tagString(s.tag),u=`Value may be parsed as either ${c} or ${l}`;o(i,"TAG_RESOLVE_FAILED",u,!0)}}return a}$_.composeScalar=sF});var W_=$(B_=>{"use strict";function uF(e,t,r){if(t){r??(r=t.length);for(let n=r-1;n>=0;--n){let i=t[n];switch(i.type){case"space":case"comment":case"newline":e-=i.source.length;continue}for(i=t[++n];i?.type==="space";)e+=i.source.length,i=t[++n];break}}return e}B_.emptyScalarPosition=uF});var V_=$(Iy=>{"use strict";var dF=Gl(),fF=De(),pF=x_(),q_=D_(),mF=uc(),hF=W_(),gF={composeNode:L_,composeEmptyNode:_y};function L_(e,t,r,n){let i=e.atKey,{spaceBefore:o,comment:a,anchor:s,tag:c}=r,l,u=!0;switch(t.type){case"alias":l=vF(e,t,n),(s||c)&&n(t,"ALIAS_PROPS","An alias node must not specify any properties");break;case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":case"block-scalar":l=q_.composeScalar(e,t,c,n),s&&(l.anchor=s.source.substring(1));break;case"block-map":case"block-seq":case"flow-collection":try{l=pF.composeCollection(gF,e,t,r,n),s&&(l.anchor=s.source.substring(1))}catch(f){let d=f instanceof Error?f.message:String(f);n(t,"RESOURCE_EXHAUSTION",d)}break;default:{let f=t.type==="error"?t.message:`Unsupported token (type: ${t.type})`;n(t,"UNEXPECTED_TOKEN",f),u=!1}}return l??(l=_y(e,t.offset,void 0,null,r,n)),s&&l.anchor===""&&n(s,"BAD_ALIAS","Anchor cannot be an empty string"),i&&e.options.stringKeys&&(!fF.isScalar(l)||typeof l.value!="string"||l.tag&&l.tag!=="tag:yaml.org,2002:str")&&n(c??t,"NON_STRING_KEY","With stringKeys, all keys must be strings"),o&&(l.spaceBefore=!0),a&&(t.type==="scalar"&&t.source===""?l.comment=a:l.commentBefore=a),e.options.keepSourceTokens&&u&&(l.srcToken=t),l}function _y(e,t,r,n,{spaceBefore:i,comment:o,anchor:a,tag:s,end:c},l){let u={type:"scalar",offset:hF.emptyScalarPosition(t,r,n),indent:-1,source:""},f=q_.composeScalar(e,u,s,l);return a&&(f.anchor=a.source.substring(1),f.anchor===""&&l(a,"BAD_ALIAS","Anchor cannot be an empty string")),i&&(f.spaceBefore=!0),o&&(f.comment=o,f.range[2]=c),f}function vF({options:e},{offset:t,source:r,end:n},i){let o=new dF.Alias(r.substring(1));o.source===""&&i(t,"BAD_ALIAS","Alias cannot be an empty string"),o.source.endsWith(":")&&i(t+r.length-1,"BAD_ALIAS","Alias ending in : is ambiguous",!0);let a=t+r.length,s=mF.resolveEnd(n,a,e.strict,i);return o.range=[t,a,s.offset],s.comment&&(o.comment=s.comment),o}Iy.composeEmptyNode=_y;Iy.composeNode=L_});var H_=$(F_=>{"use strict";var wF=fu(),M_=V_(),yF=uc(),kF=gu();function bF(e,t,{offset:r,start:n,value:i,end:o},a){let s=Object.assign({_directives:t},e),c=new wF.Document(void 0,s),l={atKey:!1,atRoot:!0,directives:c.directives,options:c.options,schema:c.schema},u=kF.resolveProps(n,{indicator:"doc-start",next:i??o?.[0],offset:r,onError:a,parentIndent:0,startOnNewline:!0});u.found&&(c.directives.docStart=!0,i&&(i.type==="block-map"||i.type==="block-seq")&&!u.hasNewline&&a(u.end,"MISSING_CHAR","Block collection cannot start on same line with directives-end marker")),c.contents=i?M_.composeNode(l,i,u,a):M_.composeEmptyNode(l,u.end,n,null,u,a);let f=c.contents.range[2],d=yF.resolveEnd(o,f,!1,a);return d.comment&&(c.comment=d.comment),c.range=[r,f,d.offset],c}F_.composeDoc=bF});var Py=$(J_=>{"use strict";var AF=Xf("process"),RF=gw(),NF=fu(),vu=hu(),Q_=De(),SF=H_(),EF=uc();function wu(e){if(typeof e=="number")return[e,e+1];if(Array.isArray(e))return e.length===2?e:[e[0],e[1]];let{offset:t,source:r}=e;return[t,t+(typeof r=="string"?r.length:1)]}function U_(e){let t="",r=!1,n=!1;for(let i=0;i<e.length;++i){let o=e[i];switch(o[0]){case"#":t+=(t===""?"":n?`
|
|
103
|
+
|
|
104
|
+
`:`
|
|
105
|
+
`)+(o.substring(1)||" "),r=!0,n=!1;break;case"%":e[i+1]?.[0]!=="#"&&(i+=1),r=!1;break;default:r||(n=!0),r=!1}}return{comment:t,afterEmptyLine:n}}var xy=class{constructor(t={}){this.doc=null,this.atDirectives=!1,this.prelude=[],this.errors=[],this.warnings=[],this.onError=(r,n,i,o)=>{let a=wu(r);o?this.warnings.push(new vu.YAMLWarning(a,n,i)):this.errors.push(new vu.YAMLParseError(a,n,i))},this.directives=new RF.Directives({version:t.version||"1.2"}),this.options=t}decorate(t,r){let{comment:n,afterEmptyLine:i}=U_(this.prelude);if(n){let o=t.contents;if(r)t.comment=t.comment?`${t.comment}
|
|
106
|
+
${n}`:n;else if(i||t.directives.docStart||!o)t.commentBefore=n;else if(Q_.isCollection(o)&&!o.flow&&o.items.length>0){let a=o.items[0];Q_.isPair(a)&&(a=a.key);let s=a.commentBefore;a.commentBefore=s?`${n}
|
|
107
|
+
${s}`:n}else{let a=o.commentBefore;o.commentBefore=a?`${n}
|
|
108
|
+
${a}`:n}}if(r){for(let o=0;o<this.errors.length;++o)t.errors.push(this.errors[o]);for(let o=0;o<this.warnings.length;++o)t.warnings.push(this.warnings[o])}else t.errors=this.errors,t.warnings=this.warnings;this.prelude=[],this.errors=[],this.warnings=[]}streamInfo(){return{comment:U_(this.prelude).comment,directives:this.directives,errors:this.errors,warnings:this.warnings}}*compose(t,r=!1,n=-1){for(let i of t)yield*this.next(i);yield*this.end(r,n)}*next(t){switch(AF.env.LOG_STREAM&&console.dir(t,{depth:null}),t.type){case"directive":this.directives.add(t.source,(r,n,i)=>{let o=wu(t);o[0]+=r,this.onError(o,"BAD_DIRECTIVE",n,i)}),this.prelude.push(t.source),this.atDirectives=!0;break;case"document":{let r=SF.composeDoc(this.options,this.directives,t,this.onError);this.atDirectives&&!r.directives.docStart&&this.onError(t,"MISSING_CHAR","Missing directives-end/doc-start indicator line"),this.decorate(r,!1),this.doc&&(yield this.doc),this.doc=r,this.atDirectives=!1;break}case"byte-order-mark":case"space":break;case"comment":case"newline":this.prelude.push(t.source);break;case"error":{let r=t.source?`${t.message}: ${JSON.stringify(t.source)}`:t.message,n=new vu.YAMLParseError(wu(t),"UNEXPECTED_TOKEN",r);this.atDirectives||!this.doc?this.errors.push(n):this.doc.errors.push(n);break}case"doc-end":{if(!this.doc){let n="Unexpected doc-end without preceding document";this.errors.push(new vu.YAMLParseError(wu(t),"UNEXPECTED_TOKEN",n));break}this.doc.directives.docEnd=!0;let r=EF.resolveEnd(t.end,t.offset+t.source.length,this.doc.options.strict,this.onError);if(this.decorate(this.doc,!0),r.comment){let n=this.doc.comment;this.doc.comment=n?`${n}
|
|
109
|
+
${r.comment}`:r.comment}this.doc.range[2]=r.offset;break}default:this.errors.push(new vu.YAMLParseError(wu(t),"UNEXPECTED_TOKEN",`Unsupported token ${t.type}`))}}*end(t=!1,r=-1){if(this.doc)this.decorate(this.doc,!0),yield this.doc,this.doc=null;else if(t){let n=Object.assign({_directives:this.directives},this.options),i=new NF.Document(void 0,n);this.atDirectives&&this.onError(r,"MISSING_CHAR","Missing directives-end indicator line"),i.range=[0,r,r],this.decorate(i,!1),yield i}}};J_.Composer=xy});var G_=$(Fp=>{"use strict";var CF=Sy(),_F=Cy(),IF=hu(),z_=tu();function xF(e,t=!0,r){if(e){let n=(i,o,a)=>{let s=typeof i=="number"?i:Array.isArray(i)?i[0]:i.offset;if(r)r(s,o,a);else throw new IF.YAMLParseError([s,s+1],o,a)};switch(e.type){case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return _F.resolveFlowScalar(e,t,n);case"block-scalar":return CF.resolveBlockScalar({options:{strict:t}},e,n)}}return null}function PF(e,t){let{implicitKey:r=!1,indent:n,inFlow:i=!1,offset:o=-1,type:a="PLAIN"}=t,s=z_.stringifyString({type:a,value:e},{implicitKey:r,indent:n>0?" ".repeat(n):"",inFlow:i,options:{blockQuote:!0,lineWidth:-1}}),c=t.end??[{type:"newline",offset:-1,indent:n,source:`
|
|
110
|
+
`}];switch(s[0]){case"|":case">":{let l=s.indexOf(`
|
|
111
|
+
`),u=s.substring(0,l),f=s.substring(l+1)+`
|
|
112
|
+
`,d=[{type:"block-scalar-header",offset:o,indent:n,source:u}];return K_(d,c)||d.push({type:"newline",offset:-1,indent:n,source:`
|
|
113
|
+
`}),{type:"block-scalar",offset:o,indent:n,props:d,source:f}}case'"':return{type:"double-quoted-scalar",offset:o,indent:n,source:s,end:c};case"'":return{type:"single-quoted-scalar",offset:o,indent:n,source:s,end:c};default:return{type:"scalar",offset:o,indent:n,source:s,end:c}}}function TF(e,t,r={}){let{afterKey:n=!1,implicitKey:i=!1,inFlow:o=!1,type:a}=r,s="indent"in e?e.indent:null;if(n&&typeof s=="number"&&(s+=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 l=e.props[0];if(l.type!=="block-scalar-header")throw new Error("Invalid block scalar header");a=l.source[0]===">"?"BLOCK_FOLDED":"BLOCK_LITERAL";break}default:a="PLAIN"}let c=z_.stringifyString({type:a,value:t},{implicitKey:i||s===null,indent:s!==null&&s>0?" ".repeat(s):"",inFlow:o,options:{blockQuote:!0,lineWidth:-1}});switch(c[0]){case"|":case">":OF(e,c);break;case'"':Ty(e,c,"double-quoted-scalar");break;case"'":Ty(e,c,"single-quoted-scalar");break;default:Ty(e,c,"scalar")}}function OF(e,t){let r=t.indexOf(`
|
|
114
|
+
`),n=t.substring(0,r),i=t.substring(r+1)+`
|
|
115
|
+
`;if(e.type==="block-scalar"){let o=e.props[0];if(o.type!=="block-scalar-header")throw new Error("Invalid block scalar header");o.source=n,e.source=i}else{let{offset:o}=e,a="indent"in e?e.indent:-1,s=[{type:"block-scalar-header",offset:o,indent:a,source:n}];K_(s,"end"in e?e.end:void 0)||s.push({type:"newline",offset:-1,indent:a,source:`
|
|
116
|
+
`});for(let c of Object.keys(e))c!=="type"&&c!=="offset"&&delete e[c];Object.assign(e,{type:"block-scalar",indent:a,props:s,source:i})}}function K_(e,t){if(t)for(let r of t)switch(r.type){case"space":case"comment":e.push(r);break;case"newline":return e.push(r),!0}return!1}function Ty(e,t,r){switch(e.type){case"scalar":case"double-quoted-scalar":case"single-quoted-scalar":e.type=r,e.source=t;break;case"block-scalar":{let n=e.props.slice(1),i=t.length;e.props[0].type==="block-scalar-header"&&(i-=e.props[0].source.length);for(let o of n)o.offset+=i;delete e.props,Object.assign(e,{type:r,source:t,end:n});break}case"block-map":case"block-seq":{let i={type:"newline",offset:e.offset+t.length,indent:e.indent,source:`
|
|
117
|
+
`};delete e.items,Object.assign(e,{type:r,source:t,end:[i]});break}default:{let n="indent"in e?e.indent:-1,i="end"in e&&Array.isArray(e.end)?e.end.filter(o=>o.type==="space"||o.type==="comment"||o.type==="newline"):[];for(let o of Object.keys(e))o!=="type"&&o!=="offset"&&delete e[o];Object.assign(e,{type:r,indent:n,source:t,end:i})}}}Fp.createScalarToken=PF;Fp.resolveAsScalar=xF;Fp.setScalarValue=TF});var X_=$(Y_=>{"use strict";var jF=e=>"type"in e?Qp(e):Hp(e);function Qp(e){switch(e.type){case"block-scalar":{let t="";for(let r of e.props)t+=Qp(r);return t+e.source}case"block-map":case"block-seq":{let t="";for(let r of e.items)t+=Hp(r);return t}case"flow-collection":{let t=e.start.source;for(let r of e.items)t+=Hp(r);for(let r of e.end)t+=r.source;return t}case"document":{let t=Hp(e);if(e.end)for(let r of e.end)t+=r.source;return t}default:{let t=e.source;if("end"in e&&e.end)for(let r of e.end)t+=r.source;return t}}}function Hp({start:e,key:t,sep:r,value:n}){let i="";for(let o of e)i+=o.source;if(t&&(i+=Qp(t)),r)for(let o of r)i+=o.source;return n&&(i+=Qp(n)),i}Y_.stringify=jF});var rI=$(tI=>{"use strict";var Oy=Symbol("break visit"),$F=Symbol("skip children"),Z_=Symbol("remove item");function Wa(e,t){"type"in e&&e.type==="document"&&(e={start:e.start,value:e.value}),eI(Object.freeze([]),e,t)}Wa.BREAK=Oy;Wa.SKIP=$F;Wa.REMOVE=Z_;Wa.itemAtPath=(e,t)=>{let r=e;for(let[n,i]of t){let o=r?.[n];if(o&&"items"in o)r=o.items[i];else return}return r};Wa.parentCollection=(e,t)=>{let r=Wa.itemAtPath(e,t.slice(0,-1)),n=t[t.length-1][0],i=r?.[n];if(i&&"items"in i)return i;throw new Error("Parent collection not found")};function eI(e,t,r){let n=r(t,e);if(typeof n=="symbol")return n;for(let i of["key","value"]){let o=t[i];if(o&&"items"in o){for(let a=0;a<o.items.length;++a){let s=eI(Object.freeze(e.concat([[i,a]])),o.items[a],r);if(typeof s=="number")a=s-1;else{if(s===Oy)return Oy;s===Z_&&(o.items.splice(a,1),a-=1)}}typeof n=="function"&&i==="key"&&(n=n(t,e))}}return typeof n=="function"?n(t,e):n}tI.visit=Wa});var Up=$(Qr=>{"use strict";var jy=G_(),DF=X_(),BF=rI(),$y="\uFEFF",Dy="",By="",Wy="",WF=e=>!!e&&"items"in e,qF=e=>!!e&&(e.type==="scalar"||e.type==="single-quoted-scalar"||e.type==="double-quoted-scalar"||e.type==="block-scalar");function LF(e){switch(e){case $y:return"<BOM>";case Dy:return"<DOC>";case By:return"<FLOW_END>";case Wy:return"<SCALAR>";default:return JSON.stringify(e)}}function VF(e){switch(e){case $y:return"byte-order-mark";case Dy:return"doc-mode";case By:return"flow-error-end";case Wy: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}Qr.createScalarToken=jy.createScalarToken;Qr.resolveAsScalar=jy.resolveAsScalar;Qr.setScalarValue=jy.setScalarValue;Qr.stringify=DF.stringify;Qr.visit=BF.visit;Qr.BOM=$y;Qr.DOCUMENT=Dy;Qr.FLOW_END=By;Qr.SCALAR=Wy;Qr.isCollection=WF;Qr.isScalar=qF;Qr.prettyToken=LF;Qr.tokenType=VF});var Vy=$(iI=>{"use strict";var yu=Up();function Gn(e){switch(e){case void 0:case" ":case`
|
|
120
|
+
`:case"\r":case" ":return!0;default:return!1}}var nI=new Set("0123456789ABCDEFabcdef"),MF=new Set("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-#;/?:@&=+$_.!~*'()"),Jp=new Set(",[]{}"),FF=new Set(` ,[]{}
|
|
121
|
+
\r `),qy=e=>!e||FF.has(e),Ly=class{constructor(){this.atEnd=!1,this.blockScalarIndent=-1,this.blockScalarKeep=!1,this.buffer="",this.flowKey=!1,this.flowLevel=0,this.indentNext=0,this.indentValue=0,this.lineEndPos=null,this.next=null,this.pos=0}*lex(t,r=!1){if(t){if(typeof t!="string")throw TypeError("source is not a string");this.buffer=this.buffer?this.buffer+t:t,this.lineEndPos=null}this.atEnd=!r;let n=this.next??"stream";for(;n&&(r||this.hasChars(1));)n=yield*this.parseNext(n)}atLineEnd(){let t=this.pos,r=this.buffer[t];for(;r===" "||r===" ";)r=this.buffer[++t];return!r||r==="#"||r===`
|
|
122
|
+
`?!0:r==="\r"?this.buffer[t+1]===`
|
|
123
|
+
`:!1}charAt(t){return this.buffer[this.pos+t]}continueScalar(t){let r=this.buffer[t];if(this.indentNext>0){let n=0;for(;r===" ";)r=this.buffer[++n+t];if(r==="\r"){let i=this.buffer[n+t+1];if(i===`
|
|
124
|
+
`||!i&&!this.atEnd)return t+n+1}return r===`
|
|
125
|
+
`||n>=this.indentNext||!r&&!this.atEnd?t+n:-1}if(r==="-"||r==="."){let n=this.buffer.substr(t,3);if((n==="---"||n==="...")&&Gn(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]===yu.BOM&&(yield*this.pushCount(1),t=t.substring(1)),t[0]==="%"){let r=t.length,n=t.indexOf("#");for(;n!==-1;){let o=t[n-1];if(o===" "||o===" "){r=n-1;break}else n=t.indexOf("#",n+1)}for(;;){let o=t[r-1];if(o===" "||o===" ")r-=1;else break}let i=(yield*this.pushCount(r))+(yield*this.pushSpaces(!0));return yield*this.pushCount(t.length-i),this.pushNewline(),"stream"}if(this.atLineEnd()){let r=yield*this.pushSpaces(!0);return yield*this.pushCount(t.length-r),yield*this.pushNewline(),"stream"}return yield yu.DOCUMENT,yield*this.parseLineStart()}*parseLineStart(){let t=this.charAt(0);if(!t&&!this.atEnd)return this.setNext("line-start");if(t==="-"||t==="."){if(!this.atEnd&&!this.hasChars(4))return this.setNext("line-start");let r=this.peek(3);if((r==="---"||r==="...")&&Gn(this.charAt(3)))return yield*this.pushCount(3),this.indentValue=0,this.indentNext=0,r==="---"?"doc":"stream"}return this.indentValue=yield*this.pushSpaces(!1),this.indentNext>this.indentValue&&!Gn(this.charAt(1))&&(this.indentNext=this.indentValue),yield*this.parseBlockStart()}*parseBlockStart(){let[t,r]=this.peek(2);if(!r&&!this.atEnd)return this.setNext("block-start");if((t==="-"||t==="?"||t===":")&&Gn(r)){let n=(yield*this.pushCount(1))+(yield*this.pushSpaces(!0));return this.indentNext=this.indentValue+1,this.indentValue+=n,"block-start"}return"doc"}*parseDocument(){yield*this.pushSpaces(!0);let t=this.getLine();if(t===null)return this.setNext("doc");let r=yield*this.pushIndicators();switch(t[r]){case"#":yield*this.pushCount(t.length-r);case void 0:return yield*this.pushNewline(),yield*this.parseLineStart();case"{":case"[":return yield*this.pushCount(1),this.flowKey=!1,this.flowLevel=1,"flow";case"}":case"]":return yield*this.pushCount(1),"doc";case"*":return yield*this.pushUntil(qy),"doc";case'"':case"'":return yield*this.parseQuotedScalar();case"|":case">":return r+=yield*this.parseBlockScalarHeader(),r+=yield*this.pushSpaces(!0),yield*this.pushCount(t.length-r),yield*this.pushNewline(),yield*this.parseBlockScalar();default:return yield*this.parsePlainScalar()}}*parseFlowCollection(){let t,r,n=-1;do t=yield*this.pushNewline(),t>0?(r=yield*this.pushSpaces(!1),this.indentValue=n=r):r=0,r+=yield*this.pushSpaces(!0);while(t+r>0);let i=this.getLine();if(i===null)return this.setNext("flow");if((n!==-1&&n<this.indentNext&&i[0]!=="#"||n===0&&(i.startsWith("---")||i.startsWith("..."))&&Gn(i[3]))&&!(n===this.indentNext-1&&this.flowLevel===1&&(i[0]==="]"||i[0]==="}")))return this.flowLevel=0,yield yu.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(qy),"flow";case'"':case"'":return this.flowKey=!0,yield*this.parseQuotedScalar();case":":{let a=this.charAt(1);if(this.flowKey||Gn(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),r=this.buffer.indexOf(t,this.pos+1);if(t==="'")for(;r!==-1&&this.buffer[r+1]==="'";)r=this.buffer.indexOf("'",r+2);else for(;r!==-1;){let o=0;for(;this.buffer[r-1-o]==="\\";)o+=1;if(o%2===0)break;r=this.buffer.indexOf('"',r+1)}let n=this.buffer.substring(0,r),i=n.indexOf(`
|
|
127
|
+
`,this.pos);if(i!==-1){for(;i!==-1;){let o=this.continueScalar(i+1);if(o===-1)break;i=n.indexOf(`
|
|
128
|
+
`,o)}i!==-1&&(r=i-(n[i-1]==="\r"?2:1))}if(r===-1){if(!this.atEnd)return this.setNext("quoted-scalar");r=this.buffer.length}return yield*this.pushToIndex(r+1,!1),this.flowLevel?"flow":"doc"}*parseBlockScalarHeader(){this.blockScalarIndent=-1,this.blockScalarKeep=!1;let t=this.pos;for(;;){let r=this.buffer[++t];if(r==="+")this.blockScalarKeep=!0;else if(r>"0"&&r<="9")this.blockScalarIndent=Number(r)-1;else if(r!=="-")break}return yield*this.pushUntil(r=>Gn(r)||r==="#")}*parseBlockScalar(){let t=this.pos-1,r=0,n;e:for(let o=this.pos;n=this.buffer[o];++o)switch(n){case" ":r+=1;break;case`
|
|
129
|
+
`:t=o,r=0;break;case"\r":{let a=this.buffer[o+1];if(!a&&!this.atEnd)return this.setNext("block-scalar");if(a===`
|
|
130
|
+
`)break}default:break e}if(!n&&!this.atEnd)return this.setNext("block-scalar");if(r>=this.indentNext){this.blockScalarIndent===-1?this.indentNext=r:this.indentNext=this.blockScalarIndent+(this.indentNext===0?1:this.indentNext);do{let o=this.continueScalar(t+1);if(o===-1)break;t=this.buffer.indexOf(`
|
|
131
|
+
`,o)}while(t!==-1);if(t===-1){if(!this.atEnd)return this.setNext("block-scalar");t=this.buffer.length}}let i=t+1;for(n=this.buffer[i];n===" ";)n=this.buffer[++i];if(n===" "){for(;n===" "||n===" "||n==="\r"||n===`
|
|
132
|
+
`;)n=this.buffer[++i];t=i-1}else if(!this.blockScalarKeep)do{let o=t-1,a=this.buffer[o];a==="\r"&&(a=this.buffer[--o]);let s=o;for(;a===" ";)a=this.buffer[--o];if(a===`
|
|
133
|
+
`&&o>=this.pos&&o+1+r>s)t=o;else break}while(!0);return yield yu.SCALAR,yield*this.pushToIndex(t+1,!0),yield*this.parseLineStart()}*parsePlainScalar(){let t=this.flowLevel>0,r=this.pos-1,n=this.pos-1,i;for(;i=this.buffer[++n];)if(i===":"){let o=this.buffer[n+1];if(Gn(o)||t&&Jp.has(o))break;r=n}else if(Gn(i)){let o=this.buffer[n+1];if(i==="\r"&&(o===`
|
|
134
|
+
`?(n+=1,i=`
|
|
135
|
+
`,o=this.buffer[n+1]):r=n),o==="#"||t&&Jp.has(o))break;if(i===`
|
|
136
|
+
`){let a=this.continueScalar(n+1);if(a===-1)break;n=Math.max(n,a-2)}}else{if(t&&Jp.has(i))break;r=n}return!i&&!this.atEnd?this.setNext("plain-scalar"):(yield yu.SCALAR,yield*this.pushToIndex(r+1,!0),t?"flow":"doc")}*pushCount(t){return t>0?(yield this.buffer.substr(this.pos,t),this.pos+=t,t):0}*pushToIndex(t,r){let n=this.buffer.slice(this.pos,t);return n?(yield n,this.pos+=n.length,n.length):(r&&(yield""),0)}*pushIndicators(){let t=0;e:for(;;){switch(this.charAt(0)){case"!":t+=yield*this.pushTag(),t+=yield*this.pushSpaces(!0);continue e;case"&":t+=yield*this.pushUntil(qy),t+=yield*this.pushSpaces(!0);continue e;case"-":case"?":case":":{let r=this.flowLevel>0,n=this.charAt(1);if(Gn(n)||r&&Jp.has(n)){r?this.flowKey&&(this.flowKey=!1):this.indentNext=this.indentValue+1,t+=yield*this.pushCount(1),t+=yield*this.pushSpaces(!0);continue e}}}break e}return t}*pushTag(){if(this.charAt(1)==="<"){let t=this.pos+2,r=this.buffer[t];for(;!Gn(r)&&r!==">";)r=this.buffer[++t];return yield*this.pushToIndex(r===">"?t+1:t,!1)}else{let t=this.pos+1,r=this.buffer[t];for(;r;)if(MF.has(r))r=this.buffer[++t];else if(r==="%"&&nI.has(this.buffer[t+1])&&nI.has(this.buffer[t+2]))r=this.buffer[t+=3];else break;return yield*this.pushToIndex(t,!1)}}*pushNewline(){let t=this.buffer[this.pos];return t===`
|
|
137
|
+
`?yield*this.pushCount(1):t==="\r"&&this.charAt(1)===`
|
|
138
|
+
`?yield*this.pushCount(2):0}*pushSpaces(t){let r=this.pos-1,n;do n=this.buffer[++r];while(n===" "||t&&n===" ");let i=r-this.pos;return i>0&&(yield this.buffer.substr(this.pos,i),this.pos=r),i}*pushUntil(t){let r=this.pos,n=this.buffer[r];for(;!t(n);)n=this.buffer[++r];return yield*this.pushToIndex(r,!1)}};iI.Lexer=Ly});var Fy=$(oI=>{"use strict";var My=class{constructor(){this.lineStarts=[],this.addNewLine=t=>this.lineStarts.push(t),this.linePos=t=>{let r=0,n=this.lineStarts.length;for(;r<n;){let o=r+n>>1;this.lineStarts[o]<t?r=o+1:n=o}if(this.lineStarts[r]===t)return{line:r+1,col:1};if(r===0)return{line:0,col:t};let i=this.lineStarts[r-1];return{line:r,col:t-i+1}}}};oI.LineCounter=My});var Qy=$(uI=>{"use strict";var HF=Xf("process"),aI=Up(),QF=Vy();function Bo(e,t){for(let r=0;r<e.length;++r)if(e[r].type===t)return!0;return!1}function sI(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 lI(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 zp(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 dc(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 Kp(e,t){if(t.length<1e5)Array.prototype.push.apply(e,t);else for(let r=0;r<t.length;++r)e.push(t[r])}function cI(e){if(e.start.type==="flow-seq-start")for(let t of e.items)t.sep&&!t.value&&!Bo(t.start,"explicit-key-ind")&&!Bo(t.sep,"map-value-ind")&&(t.key&&(t.value=t.key),delete t.key,lI(t.value)?t.value.end?Kp(t.value.end,t.sep):t.value.end=t.sep:Kp(t.start,t.sep),delete t.sep)}var Hy=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 QF.Lexer,this.onNewLine=t}*parse(t,r=!1){this.onNewLine&&this.offset===0&&this.onNewLine(0);for(let n of this.lexer.lex(t,r))yield*this.next(n);r||(yield*this.end())}*next(t){if(this.source=t,HF.env.LOG_TOKENS&&console.log("|",aI.prettyToken(t)),this.atScalar){this.atScalar=!1,yield*this.step(),this.offset+=t.length;return}let r=aI.tokenType(t);if(r)if(r==="scalar")this.atNewLine=!1,this.atScalar=!0,this.type="scalar";else{switch(this.type=r,yield*this.step(),r){case"newline":this.atNewLine=!0,this.indent=0,this.onNewLine&&this.onNewLine(this.offset+t.length);break;case"space":this.atNewLine&&t[0]===" "&&(this.indent+=t.length);break;case"explicit-key-ind":case"map-value-ind":case"seq-item-ind":this.atNewLine&&(this.indent+=t.length);break;case"doc-mode":case"flow-error-end":return;default:this.atNewLine=!1}this.offset+=t.length}else{let n=`Not a YAML token: ${t}`;yield*this.pop({type:"error",offset:this.offset,message:n,source:t}),this.offset+=t.length}}*end(){for(;this.stack.length>0;)yield*this.pop()}get sourceToken(){return{type:this.type,offset:this.offset,indent:this.indent,source:this.source}}*step(){let t=this.peek(1);if(this.type==="doc-end"&&t?.type!=="doc-end"){for(;this.stack.length>0;)yield*this.pop();this.stack.push({type:"doc-end",offset:this.offset,source:this.source});return}if(!t)return yield*this.stream();switch(t.type){case"document":return yield*this.document(t);case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return yield*this.scalar(t);case"block-scalar":return yield*this.blockScalar(t);case"block-map":return yield*this.blockMap(t);case"block-seq":return yield*this.blockSequence(t);case"flow-collection":return yield*this.flowCollection(t);case"doc-end":return yield*this.documentEnd(t)}yield*this.pop()}peek(t){return this.stack[this.stack.length-t]}*pop(t){let r=t??this.stack.pop();if(!r)yield{type:"error",offset:this.offset,source:"",message:"Tried to pop an empty stack"};else if(this.stack.length===0)yield r;else{let n=this.peek(1);switch(r.type==="block-scalar"?r.indent="indent"in n?n.indent:0:r.type==="flow-collection"&&n.type==="document"&&(r.indent=0),r.type==="flow-collection"&&cI(r),n.type){case"document":n.value=r;break;case"block-scalar":n.props.push(r);break;case"block-map":{let i=n.items[n.items.length-1];if(i.value){n.items.push({start:[],key:r,sep:[]}),this.onKeyLine=!0;return}else if(i.sep)i.value=r;else{Object.assign(i,{key:r,sep:[]}),this.onKeyLine=!i.explicitKey;return}break}case"block-seq":{let i=n.items[n.items.length-1];i.value?n.items.push({start:[],value:r}):i.value=r;break}case"flow-collection":{let i=n.items[n.items.length-1];!i||i.value?n.items.push({start:[],key:r,sep:[]}):i.sep?i.value=r:Object.assign(i,{key:r,sep:[]});return}default:yield*this.pop(),yield*this.pop(r)}if((n.type==="document"||n.type==="block-map"||n.type==="block-seq")&&(r.type==="block-map"||r.type==="block-seq")){let i=r.items[r.items.length-1];i&&!i.sep&&!i.value&&i.start.length>0&&sI(i.start)===-1&&(r.indent===0||i.start.every(o=>o.type!=="comment"||o.indent<r.indent))&&(n.type==="document"?n.end=i.start:n.items.push({start:i.start}),r.items.splice(-1,1))}}}*stream(){switch(this.type){case"directive-line":yield{type:"directive",offset:this.offset,source:this.source};return;case"byte-order-mark":case"space":case"comment":case"newline":yield this.sourceToken;return;case"doc-mode":case"doc-start":{let t={type:"document",offset:this.offset,start:[]};this.type==="doc-start"&&t.start.push(this.sourceToken),this.stack.push(t);return}}yield{type:"error",offset:this.offset,message:`Unexpected ${this.type} token in YAML stream`,source:this.source}}*document(t){if(t.value)return yield*this.lineEnd(t);switch(this.type){case"doc-start":{sI(t.start)!==-1?(yield*this.pop(),yield*this.step()):t.start.push(this.sourceToken);return}case"anchor":case"tag":case"space":case"comment":case"newline":t.start.push(this.sourceToken);return}let r=this.startBlockValue(t);r?this.stack.push(r):yield{type:"error",offset:this.offset,message:`Unexpected ${this.type} token in YAML document`,source:this.source}}*scalar(t){if(this.type==="map-value-ind"){let r=zp(this.peek(2)),n=dc(r),i;t.end?(i=t.end,i.push(this.sourceToken),delete t.end):i=[this.sourceToken];let o={type:"block-map",offset:t.offset,indent:t.indent,items:[{start:n,key:t,sep:i}]};this.onKeyLine=!0,this.stack[this.stack.length-1]=o}else yield*this.lineEnd(t)}*blockScalar(t){switch(this.type){case"space":case"comment":case"newline":t.props.push(this.sourceToken);return;case"scalar":if(t.source=this.source,this.atNewLine=!0,this.indent=0,this.onNewLine){let r=this.source.indexOf(`
|
|
139
|
+
`)+1;for(;r!==0;)this.onNewLine(this.offset+r),r=this.source.indexOf(`
|
|
140
|
+
`,r)+1}yield*this.pop();break;default:yield*this.pop(),yield*this.step()}}*blockMap(t){let r=t.items[t.items.length-1];switch(this.type){case"newline":if(this.onKeyLine=!1,r.value){let n="end"in r.value?r.value.end:void 0;(Array.isArray(n)?n[n.length-1]:void 0)?.type==="comment"?n?.push(this.sourceToken):t.items.push({start:[this.sourceToken]})}else r.sep?r.sep.push(this.sourceToken):r.start.push(this.sourceToken);return;case"space":case"comment":if(r.value)t.items.push({start:[this.sourceToken]});else if(r.sep)r.sep.push(this.sourceToken);else{if(this.atIndentedComment(r.start,t.indent)){let i=t.items[t.items.length-2]?.value?.end;if(Array.isArray(i)){Kp(i,r.start),i.push(this.sourceToken),t.items.pop();return}}r.start.push(this.sourceToken)}return}if(this.indent>=t.indent){let n=!this.onKeyLine&&this.indent===t.indent,i=n&&(r.sep||r.explicitKey)&&this.type!=="seq-item-ind",o=[];if(i&&r.sep&&!r.value){let a=[];for(let s=0;s<r.sep.length;++s){let c=r.sep[s];switch(c.type){case"newline":a.push(s);break;case"space":break;case"comment":c.indent>t.indent&&(a.length=0);break;default:a.length=0}}a.length>=2&&(o=r.sep.splice(a[1]))}switch(this.type){case"anchor":case"tag":i||r.value?(o.push(this.sourceToken),t.items.push({start:o}),this.onKeyLine=!0):r.sep?r.sep.push(this.sourceToken):r.start.push(this.sourceToken);return;case"explicit-key-ind":!r.sep&&!r.explicitKey?(r.start.push(this.sourceToken),r.explicitKey=!0):i||r.value?(o.push(this.sourceToken),t.items.push({start:o,explicitKey:!0})):this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken],explicitKey:!0}]}),this.onKeyLine=!0;return;case"map-value-ind":if(r.explicitKey)if(r.sep)if(r.value)t.items.push({start:[],key:null,sep:[this.sourceToken]});else if(Bo(r.sep,"map-value-ind"))this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:o,key:null,sep:[this.sourceToken]}]});else if(lI(r.key)&&!Bo(r.sep,"newline")){let a=dc(r.start),s=r.key,c=r.sep;c.push(this.sourceToken),delete r.key,delete r.sep,this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:a,key:s,sep:c}]})}else o.length>0?r.sep=r.sep.concat(o,this.sourceToken):r.sep.push(this.sourceToken);else if(Bo(r.start,"newline"))Object.assign(r,{key:null,sep:[this.sourceToken]});else{let a=dc(r.start);this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:a,key:null,sep:[this.sourceToken]}]})}else r.sep?r.value||i?t.items.push({start:o,key:null,sep:[this.sourceToken]}):Bo(r.sep,"map-value-ind")?this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:[],key:null,sep:[this.sourceToken]}]}):r.sep.push(this.sourceToken):Object.assign(r,{key:null,sep:[this.sourceToken]});this.onKeyLine=!0;return;case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":{let a=this.flowScalar(this.type);i||r.value?(t.items.push({start:o,key:a,sep:[]}),this.onKeyLine=!0):r.sep?this.stack.push(a):(Object.assign(r,{key:a,sep:[]}),this.onKeyLine=!0);return}default:{let a=this.startBlockValue(t);if(a){if(a.type==="block-seq"){if(!r.explicitKey&&r.sep&&!Bo(r.sep,"newline")){yield*this.pop({type:"error",offset:this.offset,message:"Unexpected block-seq-ind on same line with key",source:this.source});return}}else n&&t.items.push({start:o});this.stack.push(a);return}}}}yield*this.pop(),yield*this.step()}*blockSequence(t){let r=t.items[t.items.length-1];switch(this.type){case"newline":if(r.value){let n="end"in r.value?r.value.end:void 0;(Array.isArray(n)?n[n.length-1]:void 0)?.type==="comment"?n?.push(this.sourceToken):t.items.push({start:[this.sourceToken]})}else r.start.push(this.sourceToken);return;case"space":case"comment":if(r.value)t.items.push({start:[this.sourceToken]});else{if(this.atIndentedComment(r.start,t.indent)){let i=t.items[t.items.length-2]?.value?.end;if(Array.isArray(i)){Kp(i,r.start),i.push(this.sourceToken),t.items.pop();return}}r.start.push(this.sourceToken)}return;case"anchor":case"tag":if(r.value||this.indent<=t.indent)break;r.start.push(this.sourceToken);return;case"seq-item-ind":if(this.indent!==t.indent)break;r.value||Bo(r.start,"seq-item-ind")?t.items.push({start:[this.sourceToken]}):r.start.push(this.sourceToken);return}if(this.indent>t.indent){let n=this.startBlockValue(t);if(n){this.stack.push(n);return}}yield*this.pop(),yield*this.step()}*flowCollection(t){let r=t.items[t.items.length-1];if(this.type==="flow-error-end"){let n;do yield*this.pop(),n=this.peek(1);while(n?.type==="flow-collection")}else if(t.end.length===0){switch(this.type){case"comma":case"explicit-key-ind":!r||r.sep?t.items.push({start:[this.sourceToken]}):r.start.push(this.sourceToken);return;case"map-value-ind":!r||r.value?t.items.push({start:[],key:null,sep:[this.sourceToken]}):r.sep?r.sep.push(this.sourceToken):Object.assign(r,{key:null,sep:[this.sourceToken]});return;case"space":case"comment":case"newline":case"anchor":case"tag":!r||r.value?t.items.push({start:[this.sourceToken]}):r.sep?r.sep.push(this.sourceToken):r.start.push(this.sourceToken);return;case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":{let i=this.flowScalar(this.type);!r||r.value?t.items.push({start:[],key:i,sep:[]}):r.sep?this.stack.push(i):Object.assign(r,{key:i,sep:[]});return}case"flow-map-end":case"flow-seq-end":t.end.push(this.sourceToken);return}let n=this.startBlockValue(t);n?this.stack.push(n):(yield*this.pop(),yield*this.step())}else{let n=this.peek(2);if(n.type==="block-map"&&(this.type==="map-value-ind"&&n.indent===t.indent||this.type==="newline"&&!n.items[n.items.length-1].sep))yield*this.pop(),yield*this.step();else if(this.type==="map-value-ind"&&n.type!=="flow-collection"){let i=zp(n),o=dc(i);cI(t);let a=t.end.splice(1,t.end.length);a.push(this.sourceToken);let s={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]=s}else yield*this.lineEnd(t)}}flowScalar(t){if(this.onNewLine){let r=this.source.indexOf(`
|
|
141
|
+
`)+1;for(;r!==0;)this.onNewLine(this.offset+r),r=this.source.indexOf(`
|
|
142
|
+
`,r)+1}return{type:t,offset:this.offset,indent:this.indent,source:this.source}}startBlockValue(t){switch(this.type){case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return this.flowScalar(this.type);case"block-scalar-header":return{type:"block-scalar",offset:this.offset,indent:this.indent,props:[this.sourceToken],source:""};case"flow-map-start":case"flow-seq-start":return{type:"flow-collection",offset:this.offset,indent:this.indent,start:this.sourceToken,items:[],end:[]};case"seq-item-ind":return{type:"block-seq",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken]}]};case"explicit-key-ind":{this.onKeyLine=!0;let r=zp(t),n=dc(r);return n.push(this.sourceToken),{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:n,explicitKey:!0}]}}case"map-value-ind":{this.onKeyLine=!0;let r=zp(t),n=dc(r);return{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:n,key:null,sep:[this.sourceToken]}]}}}return null}atIndentedComment(t,r){return this.type!=="comment"||this.indent<=r?!1:t.every(n=>n.type==="newline"||n.type==="space")}*documentEnd(t){this.type!=="doc-mode"&&(t.end?t.end.push(this.sourceToken):t.end=[this.sourceToken],this.type==="newline"&&(yield*this.pop()))}*lineEnd(t){switch(this.type){case"comma":case"doc-start":case"doc-end":case"flow-seq-end":case"flow-map-end":case"map-value-ind":yield*this.pop(),yield*this.step();break;case"newline":this.onKeyLine=!1;default:t.end?t.end.push(this.sourceToken):t.end=[this.sourceToken],this.type==="newline"&&(yield*this.pop())}}};uI.Parser=Hy});var hI=$(bu=>{"use strict";var dI=Py(),UF=fu(),ku=hu(),JF=Iw(),zF=De(),KF=Fy(),fI=Qy();function pI(e){let t=e.prettyErrors!==!1;return{lineCounter:e.lineCounter||t&&new KF.LineCounter||null,prettyErrors:t}}function GF(e,t={}){let{lineCounter:r,prettyErrors:n}=pI(t),i=new fI.Parser(r?.addNewLine),o=new dI.Composer(t),a=Array.from(o.compose(i.parse(e)));if(n&&r)for(let s of a)s.errors.forEach(ku.prettifyError(e,r)),s.warnings.forEach(ku.prettifyError(e,r));return a.length>0?a:Object.assign([],{empty:!0},o.streamInfo())}function mI(e,t={}){let{lineCounter:r,prettyErrors:n}=pI(t),i=new fI.Parser(r?.addNewLine),o=new dI.Composer(t),a=null;for(let s of o.compose(i.parse(e),!0,e.length))if(!a)a=s;else if(a.options.logLevel!=="silent"){a.errors.push(new ku.YAMLParseError(s.range.slice(0,2),"MULTIPLE_DOCS","Source contains multiple documents; please use YAML.parseAllDocuments()"));break}return n&&r&&(a.errors.forEach(ku.prettifyError(e,r)),a.warnings.forEach(ku.prettifyError(e,r))),a}function YF(e,t,r){let n;typeof t=="function"?n=t:r===void 0&&t&&typeof t=="object"&&(r=t);let i=mI(e,r);if(!i)return null;if(i.warnings.forEach(o=>JF.warn(i.options.logLevel,o)),i.errors.length>0){if(i.options.logLevel!=="silent")throw i.errors[0];i.errors=[]}return i.toJS(Object.assign({reviver:n},r))}function XF(e,t,r){let n=null;if(typeof t=="function"||Array.isArray(t)?n=t:r===void 0&&t&&(r=t),typeof r=="string"&&(r=r.length),typeof r=="number"){let i=Math.round(r);r=i<1?void 0:i>8?{indent:8}:{indent:i}}if(e===void 0){let{keepUndefined:i}=r??t??{};if(!i)return}return zF.isDocument(e)&&!n?e.toString(r):new UF.Document(e,n,r).toString(r)}bu.parse=YF;bu.parseAllDocuments=GF;bu.parseDocument=mI;bu.stringify=XF});var Ur=$(Ue=>{"use strict";var ZF=Py(),eH=fu(),tH=dy(),Uy=hu(),rH=Gl(),Wo=De(),nH=Oo(),iH=jt(),oH=$o(),aH=Do(),sH=Up(),cH=Vy(),lH=Fy(),uH=Qy(),Gp=hI(),gI=Ul();Ue.Composer=ZF.Composer;Ue.Document=eH.Document;Ue.Schema=tH.Schema;Ue.YAMLError=Uy.YAMLError;Ue.YAMLParseError=Uy.YAMLParseError;Ue.YAMLWarning=Uy.YAMLWarning;Ue.Alias=rH.Alias;Ue.isAlias=Wo.isAlias;Ue.isCollection=Wo.isCollection;Ue.isDocument=Wo.isDocument;Ue.isMap=Wo.isMap;Ue.isNode=Wo.isNode;Ue.isPair=Wo.isPair;Ue.isScalar=Wo.isScalar;Ue.isSeq=Wo.isSeq;Ue.Pair=nH.Pair;Ue.Scalar=iH.Scalar;Ue.YAMLMap=oH.YAMLMap;Ue.YAMLSeq=aH.YAMLSeq;Ue.CST=sH;Ue.Lexer=cH.Lexer;Ue.LineCounter=lH.LineCounter;Ue.Parser=uH.Parser;Ue.parse=Gp.parse;Ue.parseAllDocuments=Gp.parseAllDocuments;Ue.parseDocument=Gp.parseDocument;Ue.stringify=Gp.stringify;Ue.visit=gI.visit;Ue.visitAsync=gI.visitAsync});import{AsyncLocalStorage as wI}from"node:async_hooks";import{performance as vI}from"node:perf_hooks";function mH(e=0){dH+=1,fH+=e;for(let t of pH.getStore()??[])t.gitCommands+=1,t.gitDurationMs+=e}function fc(e){let t=vI.now();try{return e()}finally{mH(vI.now()-t)}}var dH,fH,pH,pee,Yp=x(()=>{"use strict";dH=0,fH=0,pH=new wI,pee=new wI});var yI=x(()=>{"use strict"});import{existsSync as hH,readFileSync as vee}from"node:fs";import Au from"node:path";function kI(e,t){let r=t.toLowerCase();return Object.entries(e).find(([n,i])=>n.toLowerCase()===r&&i!==void 0)?.[1]}function vH(e){let t=(kI(e,"PATHEXT")??".COM;.EXE;.BAT;.CMD").split(";").map(r=>r.trim().toLowerCase()).filter(Boolean);return[...new Set([...t,".ps1"])]}function wH(e,t,r){let i=Au.win32.isAbsolute(e)||/[\\/]/u.test(e)?[""]:(kI(t,"PATH")??"").split(Au.delimiter).map(s=>s.trim().replace(/^"(.*)"$/u,"$1")).filter(Boolean),a=Au.win32.extname(e)?[e]:vH(t).map(s=>`${e}${s}`);return i.flatMap(s=>a.map(c=>s?Au.join(s,c):Au.resolve(r,c)))}function Jy(e,t,r){return wH(e,t,r).find(n=>hH(n))??e}function bI(e){if(e.some(t=>gH.test(t)))throw new Error("Windows batch check arguments must not contain shell syntax")}var gH,yee,zy=x(()=>{"use strict";gH=/[&|<>()^%"!\r\n]/u,yee=["$ProgressPreference = 'SilentlyContinue'","$encoded = $env:COMET_COMMAND_PAYLOAD","Remove-Item Env:COMET_COMMAND_PAYLOAD -ErrorAction SilentlyContinue","$json = [Text.Encoding]::UTF8.GetString([Convert]::FromBase64String($encoded))","$payload = ConvertFrom-Json $json","$commandArgs = @($payload.arguments)","& $payload.command @commandArgs","if ($null -eq $LASTEXITCODE) { if ($?) { exit 0 } else { exit 1 } }","exit $LASTEXITCODE"].join("; ")});import{spawn as See,execFileSync as yH}from"node:child_process";import Ky from"node:path";function AH(e){return e instanceof Error&&(e.code==="ETIMEDOUT"||e.killed===!0&&e.signal==="SIGTERM")}function Xp(e,t,r={}){let n=r.timeoutMs??kH,i=r.maxBufferBytes??bH;if(!Number.isSafeInteger(n)||n<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=Ky.resolve(r.cwd??process.cwd()),a=r.env??process.env,s=process.platform==="win32"?Jy(e,a,o):e,c=Ky.win32.extname(s).toLowerCase(),l=c===".bat"||c===".cmd";process.platform==="win32"&&l&&bI(t);try{let u=()=>yH(s,[...t],{cwd:o,env:a,...r.input!==void 0?{input:r.input}:{},encoding:"utf8",stdio:[r.input===void 0?"ignore":"pipe","pipe","pipe"],timeout:n,killSignal:"SIGKILL",maxBuffer:i,windowsHide:!0,shell:process.platform==="win32"&&l});return/^(?:git|git\.exe)$/iu.test(Ky.win32.basename(e))?fc(u):u()}catch(u){let f=typeof u.stderr=="string"?u.stderr.trim():Buffer.isBuffer(u.stderr)?u.stderr.toString("utf8").trim():"";throw new Ru(e,t,f,{cause:u,timedOut:AH(u)})}}var kH,bH,Ru,Nu=x(()=>{"use strict";yI();Yp();zy();kH=6e4,bH=8*1024*1024,Ru=class extends Error{constructor(r,n,i,o){super(`${r} ${n.join(" ")} failed${i?`: ${i}`:""}`,o);this.command=r;this.args=n;this.stderr=i;this.name="ExternalCommandError",this.timedOut=o?.timedOut===!0}command;args;stderr;timedOut}});var AI=x(()=>{"use strict"});import{execFileSync as NH}from"child_process";import RI from"fs";import qo from"path";import{AsyncLocalStorage as Yy}from"node:async_hooks";function Zp(e){return Su.getStore()?e():Su.run(new Map,e)}function EH(e){let t=Su.getStore();for(let r of e)t?.set(Lo(r.root),e);return e}function Eu(e,t){return fc(()=>NH("git",["-C",e,...t],{encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:1e4,windowsHide:!0}).trim())}function ye(e,t){return Lo(e)===Lo(t)}function Lo(e){let t=qo.resolve(e);try{let r=RI.realpathSync.native(t);return process.platform==="win32"?r.toLowerCase():r}catch{return process.platform==="win32"?t.toLowerCase():t}}function ue(e){let t=SH.getStore()?.get(Lo(e));if(t)return{...t};try{let r=NI.getStore()?.get(Lo(e)),n=Su.getStore()?.get(r??Lo(e));if(n){let c=Gy(r??e,n);if(c)return c;if(n.length===0)return{isGitWorktree:!1,isSecondaryWorktree:!1,currentWorktreeRoot:null,primaryWorktreeRoot:null,currentBranch:null}}let i=SI(e),o=Gy(e,i);if(o&&RI.existsSync(qo.join(e,".git")))return o;let a=qo.resolve(Eu(e,["rev-parse","--show-toplevel"])),s=Gy(a,i);if(!s)throw new Error("Current worktree is missing from Git worktree list");return s}catch{return{isGitWorktree:!1,isSecondaryWorktree:!1,currentWorktreeRoot:null,primaryWorktreeRoot:null,currentBranch:null}}}function em(e){try{let t=Su.getStore()?.get(NI.getStore()?.get(Lo(e))??Lo(e));return t?t.map(r=>({...r})):SI(e)}catch{return[]}}function SI(e){let t=CH(Eu(e,["worktree","list","--porcelain","-z"]));return EH(t),t.map(r=>({...r}))}function CH(e){let t=e.split("\0"),r=[],n=null;for(let i of t)i.startsWith("worktree ")?(n&&r.push(n),n={root:qo.resolve(i.slice(9)),branch:null,detached:!1}):n&&i.startsWith("branch refs/heads/")?n.branch=i.slice(18):n&&i==="detached"&&(n.detached=!0);return n&&r.push(n),r}function Yt(e){return em(e).map(t=>t.root)}function Gy(e,t){let r=t.find(o=>ye(qo.resolve(o.root),qo.resolve(e)));if(!r)return null;let n=qo.resolve(t[0].root),i=qo.resolve(r.root);return{isGitWorktree:!0,isSecondaryWorktree:!ye(n,i),currentWorktreeRoot:i,primaryWorktreeRoot:n,currentBranch:r.branch}}function Cu(e,t){try{return Eu(e,["check-ref-format","--branch",t]),Eu(e,["show-ref","--verify",`refs/heads/${t}`]),!0}catch{return!1}}function pe(e,t){try{let r=Eu(e,["rev-parse","--verify",`${t}^{commit}`]).toLowerCase();return/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u.test(r)?r:null}catch{return null}}var Su,NI,SH,it=x(()=>{"use strict";Yp();Nu();AI();zy();Su=new Yy,NI=new Yy,SH=new Yy});import{execFileSync as _H}from"node:child_process";function EI(e,t,r=xH){try{return fc(()=>_H("git",["-C",e,...t],{encoding:"utf8",stdio:["ignore","pipe","pipe"],timeout:IH,killSignal:"SIGKILL",maxBuffer:r,windowsHide:!0}))}catch(n){let i=typeof n.stderr=="string"?n.stderr.trim():Buffer.isBuffer(n.stderr)?n.stderr.toString("utf8").trim():"";throw new Xy(e,t,i)}}function te(e,t){return EI(e,t).trim()}function Vo(e){return te(e,["status","--porcelain=v1","-z","--untracked-files=all"])===""}function Zy(e,t){te(e,["check-ref-format","--branch",t])}function pc(e){return PH(EI(e,["status","--porcelain=v1","-z","--untracked-files=all"]))}function PH(e){return[...new Set(TH(e).flatMap(t=>t.paths.map(r=>r.replaceAll("\\","/"))))].sort()}function TH(e){if(!e)return[];let t=e.split("\0").filter(Boolean),r=[];for(let n=0;n<t.length;n+=1){let i=t[n];if(i.length<4)throw new Error("Git status returned an invalid porcelain record");let o=[i.slice(3)];if(i[0]==="R"||i[0]==="C"||i[1]==="R"||i[1]==="C"){let a=t[n+1];if(!a)throw new Error("Git status returned an incomplete rename record");o.push(a),n+=1}r.push({status:i.slice(0,2),paths:o})}return r}function CI(e,t){try{let n=te(e,["config","--get",`branch.${t}.remote`]);if(n&&n!==".")return n}catch{}let r=te(e,["remote"]).split(/\r?\n/u).map(n=>n.trim()).filter(Boolean);if(r.includes("origin"))return"origin";if(r.length===1)return r[0];throw new Error(r.length===0?"Native workspace finish requires a configured Git remote":`Native workspace finish requires an unambiguous Git remote: ${r.join(", ")}`)}var IH,xH,Xy,Sr=x(()=>{"use strict";Yp();Nu();IH=3e4,xH=8*1024*1024,Xy=class extends Error{constructor(r,n,i){super(`git ${n.join(" ")} failed${i?`: ${i}`:""}`);this.cwd=r;this.args=n;this.stderr=i;this.name="GitCommandError"}cwd;args;stderr}});function $H(e){return e.toLowerCase().startsWith(".env")}function _I(e){let r=e.replaceAll("\\","/").split("/").filter(Boolean).map(n=>n.toLowerCase());return r.some(n=>$H(n))?"environment-file":r.some(n=>jH.has(n))?"credential-config":r.includes(".git")?"git-metadata":r.some(n=>OH.has(n))?"dependency-or-cache":r.join("/")===".comet/config.yaml"?"comet-config":r.join("/")===".comet/current-change.json"?"comet-selection":null}var OH,jH,II=x(()=>{"use strict";OH=new Set([".cache",".git",".gradle",".gnupg",".mypy_cache",".next",".npm",".pnpm-store",".pytest_cache",".ssh",".turbo",".venv",".yarn","__pycache__","node_modules","venv"]),jH=new Set([".git-credentials",".netrc",".npmrc",".pypirc","auth.json","credentials.json"])});function Mo(e){return e!==0&&e!==0n&&e!=="0"}function _u(e,t){return Mo(e.dev)&&Mo(t.dev)&&Mo(e.ino)&&Mo(t.ino)}function ot(e,t){let r=Mo(e.dev)&&Mo(t.dev);if(r&&e.dev!==t.dev)return!1;let n=Mo(e.ino)&&Mo(t.ino);return n&&e.ino!==t.ino?!1:r&&n?!0:e.birthtime===t.birthtime}var mc=x(()=>{"use strict"});var hc=x(()=>{"use strict";mc()});import{createHash as DH}from"node:crypto";import{promises as Xt}from"node:fs";import Jr from"node:path";import{TextDecoder as PI}from"node:util";function tm(e,t){let r=Jr.relative(e,t);return r===""||!Jr.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${Jr.sep}`)}function OI(e){let t=Jr.posix.normalize(e);if(e.length===0||e!==e.trim()||e.includes("\\")||Array.from(e).some(i=>{let o=i.codePointAt(0)??0;return o<=31||o===127})||Jr.posix.isAbsolute(t)||/^(?:[A-Za-z]:|~)/u.test(e)||e.split("/").includes("..")||t!==e||t==="."||e.endsWith("/"))throw new Error(`Native artifact ref must be normalized and relative: ${e}`);let r=e.toLowerCase(),n=_I(e);if(n||r==="runtime"||r.startsWith("runtime/"))throw new Error(`Native artifact ref is excluded as sensitive (${n??"native-runtime"}): ${e}`);return e}function jI(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("Native artifact byte limit must be a positive integer");return e}function BH(e,t){return ot({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function Fo(e,t){let r={...e,birthtime:e.birthtimeMs},n={...t,birthtime:t.birthtimeMs};return ot(r,n)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.size===t.size}async function xI(e){let t=await Xt.lstat(e);if(!t.isDirectory()||t.isSymbolicLink())throw new Error(`Native artifact parent must be a real directory: ${e}`);return{path:e,realPath:await Xt.realpath(e),dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs}}async function $I(e,t){let r=Jr.resolve(e),n=Jr.resolve(t);if(!tm(r,n))throw new Error("Native artifact path is outside its root");let i=[await xI(r)],o=r;for(let a of Jr.relative(r,n).split(Jr.sep).filter(Boolean)){o=Jr.join(o,a);let s=await xI(o);if(!tm(i[0].realPath,s.realPath))throw new Error(`Native artifact parent resolves outside its root: ${o}`);i.push(s)}return i}async function rm(e){for(let t of e){let r=await Xt.lstat(t.path);if(!r.isDirectory()||r.isSymbolicLink()||!BH(t,r)||await Xt.realpath(t.path)!==t.realPath)throw new Error(`Native artifact parent changed while reading: ${t.path}`)}}async function Pe(e){let t=OI(e.ref),r=e.maxBytes===null?null:jI(e.maxBytes??TI),n=Jr.resolve(e.root,...t.split("/")),i=await $I(e.root,Jr.dirname(n));await e.hooks?.afterParentChainCaptured?.();let o=await Xt.lstat(n);if(!o.isFile()||o.isSymbolicLink())throw new Error(`Native artifact must be a regular file: ${t}`);if(r!==null&&o.size>r)throw new Error(`Native artifact exceeds ${r} bytes: ${t}`);let a=await Xt.realpath(n);if(!tm(i[0].realPath,a))throw new Error(`Native artifact resolves outside its root: ${t}`);let s=await Xt.open(n,"r");try{let[c,l,u]=await Promise.all([s.stat(),Xt.lstat(n),Xt.realpath(n)]);if(await rm(i),!c.isFile()||!l.isFile()||l.isSymbolicLink()||u!==a||!Fo(o,c)||!Fo(c,l))throw new Error(`Native artifact changed while opening: ${t}`);await e.hooks?.afterOpen?.();let f=[],d=0,p=Buffer.allocUnsafe(r===null?64*1024:Math.min(64*1024,r+1));for(;;){let y=r===null?p.length:r+1-d,R=await s.read(p,0,Math.min(p.length,y),null);if(R.bytesRead===0)break;if(d+=R.bytesRead,r!==null&&d>r)throw new Error(`Native artifact exceeds ${r} bytes: ${t}`);f.push(Buffer.from(p.subarray(0,R.bytesRead)))}await e.hooks?.beforeFinalCheck?.();let[m,h,g]=await Promise.all([s.stat(),Xt.lstat(n),Xt.realpath(n)]);if(await rm(i),!h.isFile()||h.isSymbolicLink()||g!==a||!Fo(c,m)||!Fo(c,h))throw new Error(`Native artifact changed while reading: ${t}`);let v=Buffer.concat(f,d),w;try{w=new PI("utf-8",{fatal:!0}).decode(v)}catch(y){throw new Error(`Native artifact is not valid UTF-8: ${t}`,{cause:y})}return{ref:t,size:d,hash:e.includeHash===!1?null:DH("sha256").update(v).digest("hex"),text:w}}finally{await s.close()}}async function ek(e){let t=OI(e.ref),r=jI(e.maxBytes),n=Jr.resolve(e.root,...t.split("/")),i=await $I(e.root,Jr.dirname(n));await e.hooks?.afterParentChainCaptured?.();let o=await Xt.lstat(n);if(!o.isFile()||o.isSymbolicLink())throw new Error(`Native artifact must be a regular file: ${t}`);let a=await Xt.realpath(n);if(!tm(i[0].realPath,a))throw new Error(`Native artifact resolves outside its root: ${t}`);let s=await Xt.open(n,"r");try{let[c,l,u]=await Promise.all([s.stat(),Xt.lstat(n),Xt.realpath(n)]);if(await rm(i),!c.isFile()||!l.isFile()||l.isSymbolicLink()||u!==a||!Fo(o,c)||!Fo(c,l))throw new Error(`Native artifact changed while opening: ${t}`);await e.hooks?.afterOpen?.();let f=Math.min(c.size,r),d=[],p=0,m=Buffer.allocUnsafe(Math.min(64*1024,r));for(;p<f;){let N=await s.read(m,0,Math.min(m.length,f-p),null);if(N.bytesRead===0)break;p+=N.bytesRead,d.push(Buffer.from(m.subarray(0,N.bytesRead)))}await e.hooks?.beforeFinalCheck?.();let[h,g,v]=await Promise.all([s.stat(),Xt.lstat(n),Xt.realpath(n)]);if(await rm(i),!g.isFile()||g.isSymbolicLink()||v!==a||!Fo(c,h)||!Fo(c,g)||p!==f)throw new Error(`Native artifact changed while reading: ${t}`);let w=c.size>r,y=Buffer.concat(d,p),R;try{R=new PI("utf-8",{fatal:!0}).decode(y,{stream:w})}catch(N){throw new Error(`Native artifact prefix is not valid UTF-8: ${t}`,{cause:N})}return{ref:t,size:c.size,text:R,truncated:w}}finally{await s.close()}}var TI,Er=x(()=>{"use strict";II();hc();TI=Number.MAX_SAFE_INTEGER});import{promises as WH}from"node:fs";import qH from"node:path";function im(e,t,r=""){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object${r}`);return e}function nm(e,t,r){let n=Object.keys(e).filter(o=>!t.has(o)),i=[...t].filter(o=>!(o in e));if(n.length>0||i.length>0){let o=[...i.length>0?[`missing ${i.join(", ")}`]:[],...n.length>0?[`unexpected ${n.join(", ")}`]:[],`expected ${[...t].join(", ")}`];throw new Error(`${r} fields are invalid: ${o.join("; ")}`)}}function BI(e,t){if(!Array.isArray(e)||!e.every(r=>typeof r=="string"))throw new Error(`${t} must be an array of strings`);return[...new Set(e)].sort((r,n)=>r.localeCompare(n,"en"))}function QH(e){let t=new Map(e.map(o=>[o.name,o])),r=new Set,n=new Set,i=o=>{if(!n.has(o)){if(r.has(o))throw new Error(`Native children dependency cycle includes ${o}`);r.add(o);for(let a of t.get(o).depends_on)i(a);r.delete(o),n.add(o)}};for(let o of e)i(o.name)}function WI(e,t,r=[]){let n=new Set(t);for(let a of e){let s=a.covers.filter(c=>!n.has(c));if(s.length>0)throw new Error(`Native child ${a.name} covers unknown acceptance: ${s.join(", ")}`)}let i=new Set(e.flatMap(a=>a.covers)),o=r.filter(a=>!i.has(a));if(o.length>0)throw new Error(`Native children do not cover parent acceptance: ${o.join(", ")}`)}function MI(e,t,r){let n={missing:[],extra:[],mismatched:[],uncovered:[],unknownCovers:[]};if(e.schema===rk&&e.acceptance_index){let i=r.requiredAcceptanceIds??[],o=r.allowedAcceptanceIds??t??i,a=Object.keys(e.acceptance_index);n.missing=i.filter(l=>!(l in e.acceptance_index)),n.extra=a.filter(l=>!o.includes(l));let s=new Map((r.acceptanceCatalog??[]).map(l=>[l.id,l]));for(let l of a){let u=s.get(l),f=e.acceptance_index[l];u&&f&&(f.source!==u.source||f.text!==u.text)&&n.mismatched.push(l)}let c=new Set(a);for(let l of e.children)n.unknownCovers.push(...l.covers.filter(u=>!c.has(u)));return n.uncovered=i.filter(l=>!qI(e.children,l)),LI(n)?n:null}if(e.schema===qa&&t){let i=new Set(t);for(let o of e.children)n.unknownCovers.push(...o.covers.filter(a=>!i.has(a)));return n.uncovered=(r.requiredAcceptanceIds??[]).filter(o=>!qI(e.children,o)),LI(n)?n:null}return null}function qI(e,t){return e.some(r=>r.covers.includes(t))}function LI(e){return e.missing.length>0||e.extra.length>0||e.mismatched.length>0||e.uncovered.length>0||e.unknownCovers.length>0}function fn(e){return{acceptanceCatalog:e.acceptance,requiredAcceptanceIds:[],allowedAcceptanceIds:e.acceptance.map(({id:t})=>t)}}function UH(e){let t=im(e,"Native children acceptance_index",' keyed by acceptance ID, for example A1: { source: brief.md, text: "Full acceptance text" }'),r={};for(let[n,i]of Object.entries(t)){let o=im(i,`Native children acceptance_index.${n}`);if(nm(o,new Set(["source","text"]),`Native children acceptance_index.${n}`),typeof o.source!="string"||o.source.length===0)throw new Error(`Native children acceptance_index.${n}.source must be a non-empty string`);if(typeof o.text!="string"||o.text.length===0)throw new Error(`Native children acceptance_index.${n}.text must be a non-empty string`);r[n]={source:o.source,text:o.text}}return r}function JH(e,t,r){let n=r.requiredAcceptanceIds??[],i=r.allowedAcceptanceIds??t??n,o=Object.keys(e),a=n.filter(c=>!(c in e)),s=o.filter(c=>!i.includes(c));if(a.length>0||s.length>0)throw new Error(`Native children acceptance_index must match the required acceptance: missing ${a.join(", ")||"none"}; extra ${s.join(", ")||"none"}`)}function om(e,t,r={}){let n=(0,VI.parseDocument)(e,{uniqueKeys:!0});if(n.errors.length>0)throw new Error(`Native children contract is invalid YAML: ${n.errors[0].message}`);let i=im(n.toJS({mapAsMap:!1}),"Native children contract"),o=i.schema;if(o!==qa&&o!==Ho)throw nm(i,DI,"Native children contract"),new Error(`Native children schema must be ${qa} or ${Ho}`);let a=o===qa?"v1":"acceptance_index"in i?"indexed-v2":Array.isArray(i.children)&&i.children.every(d=>!d||typeof d!="object"||!("summary"in d))&&i.children.some(d=>d&&typeof d=="object"&&"covers"in d)?"referenced-v2":"summary-v2";if(a==="referenced-v2"&&!r.acceptanceCatalog)throw new Error("Native referenced children require the current acceptance catalog");let s=a.replace("-"," ");if(nm(i,a==="indexed-v2"?VH:DI,"Native children contract"),!Array.isArray(i.children)||i.children.length===0)throw new Error("Native children must be a non-empty array");let c=i.children.map((d,p)=>{let m=im(d,`Native child ${p}`);if(nm(m,a==="indexed-v2"||a==="referenced-v2"?HH:a==="summary-v2"?FH:MH,`Native ${s} child fields (child ${p})`),typeof m.name!="string"||!LH.test(m.name))throw new Error(`Native child ${p} name is invalid`);let h=a==="summary-v2";if(h){if(typeof m.summary!="string"||m.summary.trim().length===0)throw new Error(`Native child ${m.name} summary must be a non-empty string`);if(m.summary.length>2e3)throw new Error(`Native child ${m.name} summary exceeds 2000 characters`)}return{name:m.name,summary:h?m.summary:null,depends_on:BI(m.depends_on,`Native child ${m.name} depends_on`),covers:a==="indexed-v2"||a==="referenced-v2"||a==="v1"?BI(m.covers,`Native child ${m.name} covers`):[]}}),l=c.map(({name:d})=>d);if(new Set(l).size!==l.length)throw new Error("Native child names must be unique");let u=new Set(l);for(let d of c){let p=d.depends_on.filter(m=>!u.has(m));if(p.length>0)throw new Error(`Native child ${d.name} depends on unknown child: ${p.join(", ")}`)}QH(c);let f=r.policy==="advisory";if(o===rk){if(a==="indexed-v2"||a==="referenced-v2"){let d=a==="indexed-v2"?UH(i.acceptance_index):{},p=[...new Set([...Object.keys(d),...r.requiredAcceptanceIds??[],...c.flatMap(v=>v.covers)])],m=new Map(r.acceptanceCatalog?.map(v=>[v.id,v])),h=Object.fromEntries(p.map(v=>{let w=m.get(v)??d[v];if(!w)throw new Error(`Native acceptance catalog is missing ${v}`);return[v,{source:w.source,text:w.text}]}));f||JH(h,t,r);let g=Object.keys(h);return f||WI(c,g,r.requiredAcceptanceIds??[]),{schema:Ho,acceptance_index:h,children:c}}return{schema:Ho,children:c}}return t&&!f&&WI(c,t),{schema:qa,children:c}}async function pn(e){let t=qH.join(e.changeDir,tk);try{await WH.lstat(t)}catch(a){if(a.code==="ENOENT")return null;throw a}let r=await Pe({root:e.changeDir,ref:tk,includeHash:!1}),n=e.policy==="advisory",i=n?{...e.validation,policy:"advisory"}:e.validation??{},o=om(r.text,e.acceptanceIds,i);return{contract:o,size:r.size,drift:n?MI(o,e.acceptanceIds,e.validation??{}):null}}function Ke(e,t,r){let n=e?.contractRef??e?.contractHash;if(t&&typeof n=="string"){let i=t.state;if(r?.stepId==="supervisor.prepare"&&r.executionOrigin&&n===i.children_contract_hash){let s=t.actionContexts[r.id].results["shape.prepare"],c=s&&t.actions.find(l=>l.stepId==="shape.prepare"&&l.status==="succeeded"&&t.actionContexts[l.id].sequence===s.sequence);if(c&&c.id===i.children_contract_ref)return c.id}if(n===i.children_contract_ref)return n;let o=t.outputs["supervisor.prepare"];if(o?.value?.contractHash===n){let s=t.actions.find(u=>u.stepId==="supervisor.prepare"&&u.status==="succeeded"&&t.actionContexts[u.id].sequence===o.sequence),c=s&&t.actionContexts[s.id].results["shape.prepare"],l=c&&t.actions.find(u=>u.stepId==="shape.prepare"&&u.status==="succeeded"&&t.actionContexts[u.id].sequence===c.sequence);if(l&&l.id===i.children_contract_ref)return l.id}}return typeof n=="string"?n:void 0}var VI,tk,qa,Ho,rk,LH,DI,VH,MH,FH,HH,Cr=x(()=>{"use strict";VI=dr(Ur(),1);Er();tk="children.yaml",qa="comet.native.children.v1",Ho="comet.native.children.v2",rk=Ho,LH=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,DI=new Set(["schema","children"]),VH=new Set(["schema","acceptance_index","children"]),MH=new Set(["name","depends_on","covers"]),FH=new Set(["name","summary","depends_on"]),HH=new Set(["name","depends_on","covers"])});import Qo from"path";import{isDeepStrictEqual as FI}from"node:util";function GI(e,t){return La[t][e]}function KH(e,t,r){let n=/^(\s*)([a-z_]+):/u.exec(e);if(!n)return null;let i=n[1].length,o=n[2];if(i===0&&o in La.en)return o;if(i===2&&t){let a=`${t}.${o}`;if(a in La.en)return a}if(i===4&&t==="knowledge"&&r==="remote"){let a=`knowledge.remote.${o}`;if(a in La.en)return a}if(i===4&&t==="knowledge"&&r==="local"){let a=`knowledge.local.${o}`;if(a in La.en)return a}return i===2&&t===null&&o==="hook"?"hook":i===2&&t==="hook"&&o==="allow_paths"?"hook.allow_paths":null}function Pu(e,t,r){let n=[],i=null,o=null;for(let g of(0,ke.stringify)(e).trimEnd().split(`
|
|
143
|
+
`)){let v=KH(g,i,o);if(v){let w=g.match(/^\s*/u)?.[0]??"";for(let y of GI(v,t).split(`
|
|
144
|
+
`))n.push(`${w}${y}`)}n.push(g),/^[a-z_]+:/u.test(g)?(g.startsWith("native:")?i="native":g.startsWith("classic:")?i="classic":g.startsWith("hook:")?i="hook":g.startsWith("memory:")?i="memory":g.startsWith("knowledge:")?i="knowledge":i=null,o=null):/^ {2}[a-z_]+:/u.test(g)&&i==="knowledge"&&(o=g.startsWith(" local:")?"local":g.startsWith(" remote:")?"remote":null)}n.push("");let a=n.join(`
|
|
145
|
+
`);if(!r)return a;let s=(0,ke.parseDocument)(r,{uniqueKeys:!0});if(s.errors.length>0)throw new Error(s.errors[0].message);let c=(0,ke.parseDocument)(a);if(!(0,ke.isMap)(s.contents)||!(0,ke.isMap)(c.contents))return a;let l=g=>{if(!(0,ke.isMap)(g))return;let v=g.items[0];g.commentBefore&&v&&(0,ke.isScalar)(v.key)&&(v.key.commentBefore=[g.commentBefore,v.key.commentBefore].filter(Boolean).join(`
|
|
146
|
+
`),g.commentBefore=void 0);for(let w of g.items)l(w.value)};l(s.contents),l(c.contents);let u=s.toJS(),f=c.get("classic",!0);if((0,ke.isMap)(f))for(let g of[...s.contents.items]){if(!(0,ke.isScalar)(g.key)||c.has(g.key))continue;let v=String(g.key.value);if(!Object.hasOwn(La.en,`classic.${v}`)||!f.has(v))continue;let w=s.get("classic",!0);if(!(0,ke.isMap)(w)){let R=s.createPair("classic",{});s.contents.items.push(R),w=R.value}if(!(0,ke.isMap)(w))continue;let y=w.items.find(R=>(0,ke.isScalar)(R.key)&&R.key.value===v);y?((0,ke.isScalar)(y.key)&&(y.key.commentBefore=[g.key.commentBefore,y.key.commentBefore].filter(Boolean).join(`
|
|
147
|
+
`)||void 0),(0,ke.isNode)(y.value)&&(0,ke.isNode)(g.value)&&(y.value.comment=[g.value.comment,y.value.comment].filter(Boolean).join(`
|
|
148
|
+
`)||void 0)):(w.items.push(g),u.classic={...u.classic,[v]:u[v]})}let d=new Set(Object.values(La).flatMap(g=>Object.values(g).flatMap(v=>v.split(`
|
|
149
|
+
`).map(w=>w.replace(/^#\s?/u,"").trim())))),p=(g,v,w,y)=>{for(let R of[...g.items])v.has(R.key)||g.delete(R.key);for(let R of v.items){let N=String((0,ke.isScalar)(R.key)?R.key.value:R.key),b=g.items.find(E=>(0,ke.isScalar)(E.key)&&(0,ke.isScalar)(R.key)?E.key.value===R.key.value:!1);if(!b){let E=s.createPair(N,y[N]);(0,ke.isScalar)(E.key)&&(0,ke.isScalar)(R.key)&&(E.key.commentBefore=R.key.commentBefore),g.items.push(E),(0,ke.isMap)(E.value)&&(0,ke.isMap)(R.value)&&p(E.value,R.value,y[N],y[N]);continue}if((0,ke.isScalar)(b.key)&&(0,ke.isScalar)(R.key)){let E=b.key.commentBefore?.split(`
|
|
150
|
+
`).filter(I=>!d.has(I.trim())).join(`
|
|
151
|
+
`);b.key.commentBefore=[R.key.commentBefore,E].filter(Boolean).join(`
|
|
152
|
+
`)||void 0}if((0,ke.isMap)(b.value)&&(0,ke.isMap)(R.value))p(b.value,R.value,w[N]??{},y[N]);else if(!FI(w[N],y[N])){let E=b.value;b.value=s.createNode(y[N]),(0,ke.isNode)(E)&&(0,ke.isNode)(b.value)&&(b.value.comment=E.comment,b.value.commentBefore=E.commentBefore,b.value.spaceBefore=E.spaceBefore)}}};p(s.contents,c.contents,u,e);let m=(g,v)=>{if((0,ke.isAlias)(g)){let w=!1;try{w=FI(g.toJS(s),v)}catch{}if(w)return g;let y=s.createNode(v);return y.comment=g.comment,y.commentBefore=g.commentBefore,y.spaceBefore=g.spaceBefore,y}if((0,ke.isMap)(g))for(let w of g.items){let y=String((0,ke.isScalar)(w.key)?w.key.value:w.key);w.value=m(w.value,v[y])}else(0,ke.isSeq)(g)&&Array.isArray(v)&&(g.items=g.items.map((w,y)=>m(w,v[y])));return g};m(s.contents,e);let h=s.toString();return r.includes(`\r
|
|
153
|
+
`)?h.replaceAll(`
|
|
154
|
+
`,`\r
|
|
155
|
+
`):h}function GH(e,t){if(typeof e!="string")throw new Error(`${t} must be a string`);let r=e.trim();if(r.length===0||Qo.posix.isAbsolute(r)||Qo.win32.isAbsolute(r)||/^(?:~|[\\/])/u.test(r))throw new Error(`${t} must be a project-relative path`);if(r===".")return[];let n=r.replaceAll("\\","/").split("/");if(n.some(i=>i===".."))throw new Error(`${t} must stay inside the project root`);if(n.some(i=>i===""||i==="."))throw new Error(`${t} must not contain empty or dot path segments`);return n}function gc(e){let t=GH(e,"native.artifact_root");return t.length===0?".":t.join("/")}function YI(e,t="docs"){let r=e??t;if(r!=="legacy"&&r!=="docs")throw new Error("classic.artifact_layout must be legacy or docs");return r}function Jo(e,t,r=!1){if(typeof e!="string")throw new Error(`${t} must be a string`);let n=e.trim().replaceAll("\\","/");if(n.length===0||Qo.posix.isAbsolute(n)||Qo.win32.isAbsolute(n)||/^(?:~|[\\/])/u.test(n))throw new Error(`${t} must be relative to its declared path base`);let i=n.split("/");if(i.some(o=>o===".."))throw new Error(`${t} must stay inside its declared path base`);if(i.some(o=>o===""||o==="."))throw new Error(`${t} must not contain empty or dot path segments`);if(!r&&/[*?]/u.test(n))throw new Error(`${t} cannot contain wildcards`);return i.join("/")}function Uo(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be a mapping`);return e}function XI(e,t,r){let n=e??t;if(n!=="en"&&n!=="zh-CN")throw new Error(`${r} must be en or zh-CN`);return n}function YH(e,t,r){let n=e??t;if(!Number.isSafeInteger(n)||n<1)throw new Error(`${r} must be a positive integer`);return n}function zI(e,t,r){let n=YH(e,t,r);if(n>Math.floor(Number.MAX_SAFE_INTEGER/(1024*1024)))throw new Error(`${r} is too large to convert to bytes safely`);return n}function XH(e){if(e===void 0)return;let t=Uo(e,"native.pending_root_move"),r=t.id,n=t.from_artifact_root,i=t.to_artifact_root,o=t.stage;if(typeof r!="string"||!/^[a-f0-9-]{8,}$/u.test(r))throw new Error("native.pending_root_move.id is invalid");if(typeof n!="string"||typeof i!="string")throw new Error("native.pending_root_move roots must be strings");if(o!=="copying"&&o!=="ready"&&o!=="switched")throw new Error("native.pending_root_move.stage is invalid");let a;if(t.cleanup!==void 0){let s=Uo(t.cleanup,"native.pending_root_move.cleanup"),c=s.kind,l=s.state,u=s.manifest_hash;if(c!=="forward-source"&&c!=="restart-staging"&&c!=="rollback-destination"&&c!=="rollback-staging")throw new Error("native.pending_root_move.cleanup.kind is invalid");if(l!=="prepared"&&l!=="quarantined"&&l!=="deleting")throw new Error("native.pending_root_move.cleanup.state is invalid");if(typeof u!="string"||!/^[a-f0-9]{64}$/u.test(u))throw new Error("native.pending_root_move.cleanup.manifest_hash is invalid");a={kind:c,state:l,manifestHash:u}}return{id:r,fromArtifactRoot:gc(n),toArtifactRoot:gc(i),stage:o,...a?{cleanup:a}:{}}}function ZH(e){if(e===void 0)return;let t=Uo(e,"native.finish");if(t.pull_request===void 0)return{};let r=Uo(t.pull_request,"native.finish.pull_request");if(r.provider!=="repository-command")throw new Error("native.finish.pull_request.provider must be repository-command");if(!Array.isArray(r.command)||r.command.length===0)throw new Error("native.finish.pull_request.command must be a non-empty array");if(r.command.length>64)throw new Error("native.finish.pull_request.command must contain at most 64 arguments");let n=r.command.map((o,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(Qo.posix.isAbsolute(n[0])||Qo.win32.isAbsolute(n[0]))throw new Error("native.finish.pull_request.command[0] must be a bare executable name or a project-relative path");let i=r.timeout_ms??zH;if(!Number.isSafeInteger(i)||i<1||i>JI)throw new Error(`native.finish.pull_request.timeout_ms must be an integer between 1 and ${JI}`);return{pull_request:{provider:"repository-command",command:n,timeout_ms:i}}}function eQ(e,t={}){let r=Uo(e,"native"),n=r.artifact_root??(t.allowMissingArtifactRoot?"docs":void 0);if(typeof n!="string")throw new Error("native.artifact_root must be a string");let i=r.clarification_mode??"batch";if(i!=="sequential"&&i!=="batch")throw new Error("native.clarification_mode must be sequential or batch");let o=r.archive_confirmation??"automatic";if(o!=="automatic"&&o!=="required")throw new Error("native.archive_confirmation must be automatic or required");let a=r.max_verify_failures??xu;if(!Number.isSafeInteger(a)||a<1)throw new Error("native.max_verify_failures must be a positive integer");let s=r.max_parallel_children===void 0?cm:r.max_parallel_children;if(!Number.isSafeInteger(s)||s<1)throw new Error("native.max_parallel_children must be a positive integer");let c=r.document_writes??"allow";if(c!=="allow"&&c!=="revert")throw new Error("native.document_writes must be allow or revert");let l=XH(r.pending_root_move),u=ZH(r.finish);return{artifact_root:gc(n),language:XI(r.language,"en","native.language"),clarification_mode:i,archive_confirmation:o,max_verify_failures:a,max_parallel_children:s,...c==="revert"?{document_writes:c}:{},...u?{finish:u}:{},...l?{pending_root_move:l}:{}}}function tQ(e,t){if(!Number.isSafeInteger(e)||Number(e)<1||Number(e)>UI)throw new Error(`${t} must be an integer between 1 and ${UI} milliseconds`);return e}function rQ(e){let t=Uo(e,"classic"),r=t.context_compression??"off";if(r!=="off"&&r!=="beta")throw new Error("classic.context_compression must be off or beta");let n=t.review_mode??"standard";if(n!=="off"&&n!=="standard"&&n!=="thorough")throw new Error("classic.review_mode must be off, standard, or thorough");let i=t.auto_transition??!0;if(typeof i!="boolean")throw new Error("classic.auto_transition must be true or false");t.check_timeout_ms!==void 0&&tQ(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:YI(t.artifact_layout),language:XI(t.language,"zh-CN","classic.language"),context_compression:r,review_mode:n,auto_transition:i,...o==="strict"?{document_evidence:o}:{},...t.check_timeout_ms!==void 0?{check_timeout_ms:t.check_timeout_ms}:{}}}function nQ(e){let r=Uo(e,"hook").allow_paths??[];if(!Array.isArray(r))throw new Error("hook.allow_paths must be an array");return{allow_paths:[...new Set(r.map((n,i)=>Jo(n,`hook.allow_paths[${i}]`)))]}}function iQ(e){if(e===void 0)return{...am};let t=Uo(e,"memory"),r=t.learning??am.learning,n=t.retrieval??am.retrieval;if(typeof r!="boolean")throw new Error("memory.learning must be true or false");if(typeof n!="boolean")throw new Error("memory.retrieval must be true or false");return{learning:r,retrieval:n}}function nk(e,t){if(e===null||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be a mapping`);return e}function oQ(e,t){if(typeof e!="string")throw new Error(`${t} must be a string`);let r=e.trim();if(r.length===0||r.includes("\\")||r.includes("\0")||Qo.posix.isAbsolute(r)||Qo.win32.isAbsolute(r)||r.startsWith("~")||r.split("/").some(i=>i===""||i==="."||i===".."))throw new Error(`${t} must be a safe project-relative glob`);if(!r.toLowerCase().endsWith(".md"))throw new Error(`${t} must target a Markdown file ending in .md`);if(r.length>HI)throw new Error(`${t} exceeds ${HI} characters`);let n=0;for(let i=0;i<r.length;i+=1)r[i]==="?"?n+=1:r[i]==="*"&&(n+=1,r[i+1]==="*"&&(i+=1));if(n>QI)throw new Error(`${t} contains more than ${QI} wildcard tokens`);return r}function aQ(e){let t=nk(e,"knowledge.local"),r=t.include??[];if(!Array.isArray(r))throw new Error("knowledge.local.include must be an array");let n={include:[...new Set(r.map((i,o)=>oQ(i,`knowledge.local.include[${o}]`)))],max_file_mb:zI(t.max_file_mb,sm.max_file_mb,"knowledge.local.max_file_mb"),max_total_mb:zI(t.max_total_mb,sm.max_total_mb,"knowledge.local.max_total_mb")};if(n.max_file_mb>n.max_total_mb)throw new Error("knowledge.local.max_file_mb must not exceed max_total_mb");return n}function sQ(e){if(typeof e!="string"||e.trim().length===0)throw new Error("knowledge.remote.endpoint must be a non-empty URL");let t;try{t=new URL(e)}catch{throw new Error("knowledge.remote.endpoint must be a valid URL")}let r=t.hostname.toLowerCase().replace(/^\[|\]$/gu,""),n=r==="localhost"||r==="127.0.0.1"||r==="::1";if(t.protocol!=="https:"&&!(t.protocol==="http:"&&n))throw new Error("knowledge.remote.endpoint must use HTTPS (HTTP is allowed for loopback)");return t.toString()}function cQ(e){let t=nk(e,"knowledge.remote"),r=sQ(t.endpoint),n=t.token_env;if(n!==void 0&&(typeof n!="string"||!/^[A-Za-z_][A-Za-z0-9_]*$/u.test(n)))throw new Error("knowledge.remote.token_env must be an environment variable name");let i=t.scope;if(i!==void 0&&(typeof i!="string"||i.length>512))throw new Error("knowledge.remote.scope must be a string of at most 512 characters");let o=t.timeout_ms??5e3;if(typeof o!="number"||!Number.isSafeInteger(o)||o<100||o>3e4)throw new Error("knowledge.remote.timeout_ms must be an integer between 100 and 30000");return{endpoint:r,...n===void 0?{}:{token_env:n},...i===void 0?{}:{scope:i},timeout_ms:o}}function lQ(e){if(e===void 0)return{...KI};let t=nk(e,"knowledge"),r=t.provider??"local";if(r!=="local"&&r!=="remote")throw new Error("knowledge.provider must be local or remote");let n=t.local===void 0?void 0:aQ(t.local);if(r==="local")return{provider:r,...n?{local:n}:{}};let i=t.remote===void 0?void 0:cQ(t.remote);if(i===void 0)throw new Error("knowledge.remote must be configured when knowledge.provider is remote");return{provider:r,...n?{local:n}:{},remote:i}}function ik(e){if(e===void 0)return!0;if(typeof e!="boolean")throw new Error("change_walkthrough must be true or false");return e}function uQ(e){let t=e??!0;if(typeof t!="boolean")throw new Error("ambient_resume must be true or false");return t}function dQ(e,t,r,n,i,o,a,s){let c=e.schema!==void 0;if(!(c||e.default_workflow!==void 0||e.workflows!==void 0||!s.allowPartialProject&&e.native!==void 0)||s.allowPartialProject&&!c)return null;if(e.schema!=="comet.project.v1")throw new Error("Unsupported Comet project schema");if(e.default_workflow!=="native"&&e.default_workflow!=="classic")throw new Error("default_workflow must be native or classic");let u=e.workflows??[e.default_workflow];if(!Array.isArray(u)||u.length===0||u.some(d=>d!=="native"&&d!=="classic"))throw new Error("workflows must contain native and/or classic");let f=[...new Set(u)];if(!f.includes(e.default_workflow))throw new Error("workflows must include default_workflow");if(f.includes("native")&&!i)throw new Error("native must be a mapping");return{schema:"comet.project.v1",default_workflow:e.default_workflow,workflows:f,ambient_resume:a,change_walkthrough:ik(e.change_walkthrough),...t?{hook:t}:{},memory:r,knowledge:n,...i?{native:i}:{},...o?{classic:o}:{}}}function vc(e,t={}){let r=(0,ke.parseDocument)(e,{uniqueKeys:!0});if(r.errors.length>0)throw new Error(`Invalid .comet/config.yaml: ${r.errors[0].message}`);let n=r.toJS();if(n==null)return{value:{},config:null,ambient_resume:!0,change_walkthrough:!0};if(typeof n!="object"||Array.isArray(n))throw new Error("Invalid .comet/config.yaml: root must be a mapping");let i=n,o=uQ(i.ambient_resume),a=ik(i.change_walkthrough),s=i.hook===void 0?void 0:nQ(i.hook),c=iQ(i.memory),l=lQ(i.knowledge),u=i.native===void 0?void 0:eQ(i.native,{allowMissingArtifactRoot:t.allowMissingNativeFields}),f=i.classic===void 0?void 0:rQ(i.classic),d=dQ(i,s,c,l,u,f,o,{allowPartialProject:t.allowPartialProject??!1});return{value:i,config:d,ambient_resume:o,change_walkthrough:a,memory:c,knowledge:l,...s?{hook:s}:{},...u?{native:u}:{},...f?{classic:f}:{}}}function ZI(e){return{id:e.id,from_artifact_root:e.fromArtifactRoot,to_artifact_root:e.toArtifactRoot,stage:e.stage,...e.cleanup?{cleanup:{kind:e.cleanup.kind,state:e.cleanup.state,manifest_hash:e.cleanup.manifestHash}}:{}}}function ex(e){let t=e.knowledge??{...KI};return{schema:e.schema,default_workflow:e.default_workflow,workflows:e.workflows??[e.default_workflow],ambient_resume:e.ambient_resume,change_walkthrough:e.change_walkthrough??!0,memory:e.memory??{...am},knowledge:{provider:t.provider,...t.local?{local:{include:[...t.local.include],max_file_mb:t.local.max_file_mb??sm.max_file_mb,max_total_mb:t.local.max_total_mb??sm.max_total_mb}}:{},...t.remote?{remote:{endpoint:t.remote.endpoint,timeout_ms:t.remote.timeout_ms,...t.remote.token_env===void 0?{}:{token_env:t.remote.token_env},...t.remote.scope===void 0?{}:{scope:t.remote.scope}}}:{}},...e.hook?{hook:{allow_paths:[...e.hook.allow_paths]}}:{},...e.native?{native:{artifact_root:e.native.artifact_root,language:e.native.language,clarification_mode:e.native.clarification_mode,archive_confirmation:e.native.archive_confirmation,max_verify_failures:e.native.max_verify_failures,max_parallel_children:e.native.max_parallel_children??cm,...e.native.document_writes?{document_writes:e.native.document_writes}:{},...e.native.finish?.pull_request?{finish:{pull_request:{provider:e.native.finish.pull_request.provider,command:[...e.native.finish.pull_request.command],timeout_ms:e.native.finish.pull_request.timeout_ms}}}:{},...e.native.pending_root_move?{pending_root_move:ZI(e.native.pending_root_move)}:{}}}:{},...e.classic?{classic:{artifact_layout:e.classic.artifact_layout,language:e.classic.language,context_compression:e.classic.context_compression,review_mode:e.classic.review_mode,auto_transition:e.classic.auto_transition,...e.classic.check_timeout_ms!==void 0?{check_timeout_ms:e.classic.check_timeout_ms}:{},...e.classic.document_evidence?{document_evidence:e.classic.document_evidence}:{}}}:{}}}function mn(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:{}}function Tu(e,t){let r=ex({...t,change_walkthrough:t.change_walkthrough??ik(e.change_walkthrough)}),n=vc((0,ke.stringify)(r)).config;if(!n)throw new Error("Unsupported Comet project schema");let i={...e,schema:n.schema,default_workflow:n.default_workflow,workflows:n.workflows,ambient_resume:n.ambient_resume,change_walkthrough:n.change_walkthrough??!0};if(n.hook&&(i.hook={...mn(e.hook),allow_paths:[...n.hook.allow_paths]}),n.memory){let o=mn(e.memory);i.memory={...o,learning:n.memory.learning,retrieval:n.memory.retrieval}}if(n.knowledge){let o=mn(e.knowledge),a={...o,provider:n.knowledge.provider};if(n.knowledge.local?a.local={...mn(o.local),include:[...n.knowledge.local.include],max_file_mb:n.knowledge.local.max_file_mb,max_total_mb:n.knowledge.local.max_total_mb}:delete a.local,n.knowledge.remote){let c={...mn(o.remote),endpoint:n.knowledge.remote.endpoint,timeout_ms:n.knowledge.remote.timeout_ms,...n.knowledge.remote.token_env===void 0?{}:{token_env:n.knowledge.remote.token_env},...n.knowledge.remote.scope===void 0?{}:{scope:n.knowledge.remote.scope}};n.knowledge.remote.token_env===void 0&&delete c.token_env,n.knowledge.remote.scope===void 0&&delete c.scope,a.remote=c}else delete a.remote;i.knowledge=a}if(n.native){let o=mn(e.native),a={...o,artifact_root:n.native.artifact_root,language:n.native.language,clarification_mode:n.native.clarification_mode,archive_confirmation:n.native.archive_confirmation,max_verify_failures:n.native.max_verify_failures,max_parallel_children:n.native.max_parallel_children,...n.native.document_writes?{document_writes:n.native.document_writes}:{}};if(t.native?.document_writes==="allow"&&delete a.document_writes,n.native.finish?.pull_request){let s=mn(o.finish);a.finish={...s,pull_request:{...mn(s.pull_request),provider:n.native.finish.pull_request.provider,command:[...n.native.finish.pull_request.command],timeout_ms:n.native.finish.pull_request.timeout_ms}}}else{let s={...mn(o.finish)};delete s.pull_request,Object.keys(s).length>0?a.finish=s:delete a.finish}if(delete a.snapshot,n.native.pending_root_move){let s=mn(o.pending_root_move),c=ZI(n.native.pending_root_move),l=mn(s.cleanup),u=mn(c.cleanup);a.pending_root_move={...s,...c,...c.cleanup?{cleanup:{...l,...u}}:{}}}else delete a.pending_root_move;i.native=a}return n.classic&&(i.classic={...mn(e.classic),artifact_layout:n.classic.artifact_layout,language:n.classic.language,context_compression:n.classic.context_compression,review_mode:n.classic.review_mode,auto_transition:n.classic.auto_transition,...n.classic.check_timeout_ms!==void 0?{check_timeout_ms:n.classic.check_timeout_ms}:{},...n.classic.document_evidence?{document_evidence:n.classic.document_evidence}:{}}),i}var ke,Iu,HI,QI,xu,cm,am,sm,KI,UI,zH,JI,La,eo=x(()=>{"use strict";ke=dr(Ur(),1),Iu=Number.MAX_SAFE_INTEGER,HI=1024,QI=64,xu=5,cm=2,am={learning:!0,retrieval:!0},sm={include:[],max_file_mb:1,max_total_mb:32},KI={provider:"local"},UI=36e5,zH=12e4,JI=6e5,La={en:{schema:"# Configuration schema used by Comet. Do not edit this value.",default_workflow:"# Default workflow entered by /comet. Must also appear in workflows.",workflows:"# Workflows enabled in this project: native, classic, or both.",change_walkthrough:`# Generate a standalone HTML change walkthrough for Native and Classic. Enabling it uses extra explanation tokens.
|
|
156
|
+
# change_walkthrough: true | false (default: true)`,ambient_resume:`# Enables automatic recovery through the read-only Ambient Resume probe for both Native and Classic. Set false to disable it.
|
|
157
|
+
# ambient_resume: true | false`,memory:"# Project policy for automatic personal-memory learning and retrieval.","memory.learning":`# Allows workflow events in this project to form new personal memories automatically.
|
|
158
|
+
# learning: true | false`,"memory.retrieval":`# Allows personal memories to be injected into Agent context for this project.
|
|
159
|
+
# retrieval: true | false`,knowledge:"# Project knowledge retrieval provider used by ordinary Comet tasks.","knowledge.provider":`# Provider for project knowledge.
|
|
160
|
+
# provider: local | remote`,"knowledge.local":"# Additional project-relative Markdown globs used by the local provider.","knowledge.local.include":"# One project-relative Markdown glob per list item; appended to the built-in corpus.","knowledge.local.max_file_mb":"# Maximum size in MB for one local Markdown document. Increase it for long specifications or verification reports.","knowledge.local.max_total_mb":"# Maximum total size in MB of the local Markdown retrieval corpus.","knowledge.remote":"# Fixed Comet Retrieval API v1 settings used when provider is remote.","knowledge.remote.endpoint":"# HTTPS endpoint; loopback HTTP is allowed.","knowledge.remote.token_env":"# Optional environment variable containing the bearer token.","knowledge.remote.scope":"# Optional opaque remote knowledge scope.","knowledge.remote.timeout_ms":"# Remote request timeout in milliseconds (100-30000).",hook:"# Hook write policy shared by Native and Classic. Paths are project-relative.","hook.allow_paths":"# Project-relative directories allowed during guarded phases. Use one path per list item; empty by default.",native:"# Native workflow settings. They do not change Classic state or behavior.","native.artifact_root":"# Root directory where Native stores Comet specs and changes. Runtime data stays under .comet.","native.language":`# Artifact language used by Native workflow documents.
|
|
161
|
+
# language: en | zh-CN`,"native.clarification_mode":`# Controls how Native asks clarifying questions: batch asks every currently answerable question per round (default), sequential asks one at a time.
|
|
162
|
+
# clarification_mode: batch | sequential`,"native.archive_confirmation":`# Controls whether Native archives automatically after a successful preview or waits for explicit user confirmation.
|
|
163
|
+
# archive_confirmation: automatic | required`,"native.max_verify_failures":"# Maximum failed Verify outcomes allowed for one confirmed acceptance target before Native stops the completion loop.","native.max_parallel_children":"# Maximum dispatched Supervisor children awaiting integration and archive. Defaults to 2; single-session always uses 1. Changes apply at the next dispatch.","native.document_writes":`# Controls documentation file writes during Shape, Verify, and Archive: allow treats them as neutral instead of returning the change to Build, revert restores the strict behavior.
|
|
164
|
+
# document_writes: allow | revert`,"native.finish":"# Optional repository-owned finish providers. Native keeps commit, push, generic remote verification, and recovery ownership.",classic:"# Classic workflow settings. They do not change Native state or behavior.","classic.artifact_layout":`# Selects the Classic artifact layout. The default is docs; update preserves detected root-level legacy artifacts.
|
|
165
|
+
# artifact_layout: legacy | docs`,"classic.language":`# Artifact language used by Classic workflow documents.
|
|
166
|
+
# language: en | zh-CN`,"classic.context_compression":`# Controls beta context compression for new Classic changes.
|
|
167
|
+
# context_compression: off | beta`,"classic.review_mode":`# Sets the default review depth for new Classic changes.
|
|
168
|
+
# review_mode: off | standard | thorough`,"classic.auto_transition":`# Automatically enters the next Classic phase after a phase passes.
|
|
169
|
+
# auto_transition: true | false`,"classic.check_timeout_ms":"# Default check timeout in milliseconds (1-3600000); --timeout-ms overrides it. Default: 300000.","classic.document_evidence":`# Controls how documentation edits affect recorded check evidence: neutral keeps build and verify evidence valid when only documentation files changed, strict binds every working-tree file again.
|
|
170
|
+
# document_evidence: neutral | strict`},"zh-CN":{schema:"# Comet 使用的配置格式版本,请勿修改此值。",default_workflow:"# `/comet` 默认进入的工作流;该值也必须出现在 workflows 中。",workflows:"# 此项目启用的工作流,可填写 native、classic 或同时启用两者。",change_walkthrough:`# 是否生成可直接打开的 HTML 变更说明,同时作用于 Native 和 Classic;开启会增加讲解内容的 token 消耗。
|
|
171
|
+
# change_walkthrough: true | false(默认 true)`,ambient_resume:`# 是否启用只读的环境感知恢复探针,同时作用于 Native 和 Classic;设为 false 可关闭自动工作流恢复。
|
|
172
|
+
# ambient_resume: true | false`,memory:"# 当前项目的个人记忆自动学习与注入策略。","memory.learning":`# 是否允许当前项目通过工作流事件自动沉淀新的个人记忆。
|
|
173
|
+
# 可选值:true | false`,"memory.retrieval":`# 是否允许当前项目把个人记忆自动注入 Agent 上下文。
|
|
174
|
+
# 可选值:true | false`,knowledge:"# 普通 Comet 任务使用的项目知识检索 Provider。","knowledge.provider":`# 项目知识 Provider。
|
|
175
|
+
# 可选值:local | remote`,"knowledge.local":"# Local Provider 额外加载的项目相对 Markdown 路径。","knowledge.local.include":"# 每项填写一个项目相对 Markdown glob;会追加到内置语料。","knowledge.local.max_file_mb":"# 单个本地 Markdown 文档允许参与检索的最大 MB 数;较长的规格或验证报告可按需提高。","knowledge.local.max_total_mb":"# 本地 Markdown 检索语料允许读取的总 MB 数。","knowledge.remote":"# provider 为 remote 时使用的固定 Comet Retrieval API v1 配置。","knowledge.remote.endpoint":"# HTTPS 地址;loopback 地址允许使用 HTTP。","knowledge.remote.token_env":"# 可选的 Bearer Token 环境变量名。","knowledge.remote.scope":"# 可选的不透明远端知识库范围。","knowledge.remote.timeout_ms":"# 远端请求超时时间(毫秒,100-30000)。",hook:"# Native 和 Classic 共享的 Hook 写入策略;路径必须是项目相对路径。","hook.allow_paths":"# 在受保护阶段允许写入的项目相对目录;每项填写一个目录,默认为空。",native:"# Native 工作流配置,不会改变 Classic 的状态或行为。","native.artifact_root":"# Native 规格和 change 的存放根目录;运行时数据始终位于 .comet。","native.language":`# Native 工作流文档使用的产物语言。
|
|
176
|
+
# 可选值:en | zh-CN`,"native.clarification_mode":`# Native 提问澄清问题的方式:batch 每轮一次提出当前所有可回答的问题(默认),sequential 每轮只问一个。
|
|
177
|
+
# 可选值:batch | sequential`,"native.archive_confirmation":`# Native 归档检查成功后自动归档,或等待用户明确确认。
|
|
178
|
+
# 可选值:automatic | required`,"native.max_verify_failures":"# 同一个已确认验收目标最多允许的 Verify 失败次数;达到上限后停止完成循环。","native.max_parallel_children":"# Supervisor 已派发且尚未完成集成归档的子任务上限;默认 2,single-session 固定为 1;调整从下一轮派发生效。","native.document_writes":`# Shape、Verify 和 Archive 阶段的文档类写入处理方式:allow 视为中性写入、不再把 change 打回 Build,revert 恢复严格行为。
|
|
179
|
+
# 可选值:allow | revert`,"native.finish":"# 可选的仓库自有收尾 provider;提交、推送、通用远端核验和恢复仍由 Native 负责。",classic:"# Classic 工作流配置,不会改变 Native 的状态或行为。","classic.artifact_layout":`# Classic 产物布局;默认使用 docs,update 检测到根目录 legacy 产物时予以保留。
|
|
180
|
+
# 可选值:legacy | docs`,"classic.language":`# Classic 工作流文档使用的产物语言。
|
|
181
|
+
# 可选值:en | zh-CN`,"classic.context_compression":`# 新建 Classic change 是否启用 beta 上下文压缩。
|
|
182
|
+
# 可选值:off | beta`,"classic.review_mode":`# 新建 Classic change 默认使用的审查深度。
|
|
183
|
+
# 可选值:off | standard | thorough`,"classic.auto_transition":`# Classic 阶段通过后是否自动进入下一阶段。
|
|
184
|
+
# 可选值:true | false`,"classic.check_timeout_ms":"# 检查命令默认超时,单位毫秒,范围 1-3600000,缺省为 300000;命令行 --timeout-ms 优先。","classic.document_evidence":`# 文档编辑对已记录检查证据的影响:neutral 在只有文档文件变化时保持 build 和 verify 证据有效,strict 重新绑定工作区的全部文件。
|
|
185
|
+
# 可选值:neutral | strict`}}});import{constants as zo,promises as zr}from"fs";import{createHash as fQ}from"node:crypto";function ok(e){return"birthtimeNs"in e&&typeof e.birthtimeNs=="bigint"?e.birthtimeNs:e.birthtimeMs}function lm(e){return"ctimeNs"in e&&typeof e.ctimeNs=="bigint"?e.ctimeNs:e.ctimeMs}function Go(e){return{dev:e.dev,ino:e.ino,birthtime:ok(e)}}function pQ(e,t){let r=Go(e),n=Go(t);return _u(r,n)?ot(r,n):ot(r,n)&&ok(e)===ok(t)&&lm(e)===lm(t)&&e.size===t.size}function Ko(e,t){let r=n=>"mtimeNs"in n?n.mtimeNs:n.mtimeMs;return pQ(e,t)&&e.size===t.size&&e.mode===t.mode&&r(e)===r(t)&&lm(e)===lm(t)}async function Yo(e,t,r={}){if(!Number.isSafeInteger(t)||t<1)throw new Error("race-safe read byte limit must be a positive integer");let n=r.label??"file",i=r.bigint===!0,o=await zr.lstat(e,{bigint:i});if(!o.isFile()||o.isSymbolicLink())throw new ir("not-regular-file",`${n} must be a regular file`);if(BigInt(o.size)>BigInt(t))throw new ir("too-large",`${n} exceeds ${t} bytes`);let a=await zr.realpath(e);await r.verify?.("pre-open",{realPath:a,identity:Go(o)});let s=process.platform==="win32"?zo.O_RDONLY:zo.O_RDONLY|zo.O_NOFOLLOW|zo.O_NONBLOCK,c;try{c=await zr.open(e,s)}catch(l){throw l.code==="ELOOP"?new ir("not-regular-file",`${n} must be a regular file`,{cause:l}):l}try{let[l,u,f]=await Promise.all([c.stat({bigint:i}),zr.lstat(e,{bigint:i}),zr.realpath(e)]);if(!l.isFile()||!u.isFile()||u.isSymbolicLink()||f!==a||!Ko(o,l)||!Ko(o,u))throw new ir("changed",`${n} changed while opening`);await r.verify?.("post-open",{realPath:f,identity:Go(l)}),await r.hooks?.afterOpen?.();let d=[],p=0,m=Buffer.allocUnsafe(Math.min(64*1024,t+1));for(;;){let w=t+1-p,{bytesRead:y}=await c.read(m,0,Math.min(m.length,w),null);if(y===0)break;if(p+=y,p>t)throw new ir("too-large",`${n} exceeds ${t} bytes`);d.push(Buffer.from(m.subarray(0,y)))}await r.hooks?.beforeFinalCheck?.();let[h,g,v]=await Promise.all([c.stat({bigint:i}),zr.lstat(e,{bigint:i}),zr.realpath(e)]);if(!g.isFile()||g.isSymbolicLink()||v!==a||!Ko(o,h)||!Ko(o,g))throw new ir("changed",`${n} changed while reading`);return await r.verify?.("post-read",{realPath:v,identity:Go(h)}),{bytes:Buffer.concat(d,p),stat:h,realPath:v}}finally{await c.close()}}async function tx(e,t={}){let r=t.label??"file",n=t.bigint===!0,i=await zr.lstat(e,{bigint:n});if(!i.isFile()||i.isSymbolicLink())throw new ir("not-regular-file",`${r} must be a regular file`);let o=await zr.realpath(e);await t.verify?.("pre-open",{realPath:o,identity:Go(i)});let a=process.platform==="win32"?zo.O_RDONLY:zo.O_RDONLY|zo.O_NOFOLLOW|zo.O_NONBLOCK,s;try{s=await zr.open(e,a)}catch(c){throw c.code==="ELOOP"?new ir("not-regular-file",`${r} must be a regular file`,{cause:c}):c}try{let[c,l,u]=await Promise.all([s.stat({bigint:n}),zr.lstat(e,{bigint:n}),zr.realpath(e)]);if(!c.isFile()||!l.isFile()||l.isSymbolicLink()||u!==o||!Ko(i,c)||!Ko(i,l))throw new ir("changed",`${r} changed while opening`);await t.verify?.("post-open",{realPath:u,identity:Go(c)}),await t.hooks?.afterOpen?.();let f=fQ(t.algorithm??"sha256"),d=Buffer.allocUnsafe(64*1024);for(;;){let{bytesRead:g}=await s.read(d,0,d.length,null);if(g===0)break;f.update(d.subarray(0,g))}await t.hooks?.beforeFinalCheck?.();let[p,m,h]=await Promise.all([s.stat({bigint:n}),zr.lstat(e,{bigint:n}),zr.realpath(e)]);if(!m.isFile()||m.isSymbolicLink()||h!==o||!Ko(i,p)||!Ko(i,m))throw new ir("changed",`${r} changed while reading`);return await t.verify?.("post-read",{realPath:h,identity:Go(p)}),{digest:f.digest("hex"),stat:p,realPath:h}}finally{await s.close()}}var ir,Xo=x(()=>{"use strict";mc();ir=class extends Error{reason;constructor(t,r,n){super(r,n),this.name="RaceSafeReadError",this.reason=t}}});import{AsyncLocalStorage as mQ}from"node:async_hooks";function um(){let e=ak.getStore();return e?.active?e:null}function rx(){um()?.entries.clear()}async function dm(e){if(um()!==null)return e();let t={entries:new Map,active:!0};return ak.run(t,async()=>{try{return await e()}finally{t.active=!1,t.entries.clear()}})}async function Ri(e){return ak.run({entries:new Map,active:!1},e)}function nx(e,t){let r=e;for(let n of t)r+="\0"+(typeof n=="string"?n:JSON.stringify(n));return r}function En(e,t){return(...r)=>{let n=um();if(n===null)return t(...r);let i=nx(`async:${e}`,r),o=n.entries.get(i);if(o)return o.value;let a=t(...r).catch(s=>{throw n.entries.get(i)?.value===a&&n.entries.delete(i),s});return n.entries.set(i,{value:a}),a}}function to(e,t){return(...r)=>{let n=um();if(n===null)return t(...r);let i=nx(`sync:${e}`,r),o=n.entries.get(i);if(o)return o.value;let a=t(...r);return n.entries.set(i,{value:a}),a}}var ak,Ni=x(()=>{"use strict";ak=new mQ});import{promises as Kr}from"fs";import Je from"path";import{AsyncLocalStorage as hQ}from"node:async_hooks";async function fm(e,t,r={}){let n=Je.resolve(e),i=await ck(n,t),o=new Map,a=!1,s=d=>[d.dev,d.ino,d.mode,d.birthtimeNs,d.mtimeNs,d.ctimeNs].join(":"),c=d=>[d.dev,d.ino,d.mode,d.birthtimeNs].join(":"),l=async(d,p)=>JSON.stringify((await Kr.readdir(d,{withFileTypes:!0})).filter(m=>!p(m)).map(m=>[m.name,m.isDirectory(),m.isSymbolicLink()]).sort((m,h)=>String(m[0]).localeCompare(String(h[0]),"en"))),u=d=>{let p=o.get(d);return p||(p=(async()=>{let m=await Kr.lstat(d,{bigint:!0});if(!m.isDirectory()||m.isSymbolicLink())throw new Error(`${t} crosses a symbolic link, junction or invalid directory at ${Je.relative(n,d)||"."}`);let h=await Kr.realpath(d);if(!wc(i,h))throw new Error(`${t} resolves outside the project root`);let g=r.ignoredDirectoryEntries?.(Je.relative(n,d).replaceAll("\\","/")||".");return{stat:m,real:h,...g?{ignoreEntry:g,namespace:await l(d,g)}:{}}})(),p=p.catch(m=>{throw o.delete(d),m}),o.set(d,p)),p};await u(n);let f=async d=>{if(a)throw new Error(`${t} read session is already finished`);let p=Jo(d,t),m=n;for(let h of p.split("/").slice(0,-1))m=Je.join(m,h),await u(m);return Je.resolve(n,...p.split("/"))};return{observePath:f,async observeDirectory(d){let p=await f(d);return await u(p),p},async stat(d){let p=await f(d),m=await Kr.lstat(p,{bigint:!0});if(!m.isFile()||m.isSymbolicLink())throw new Error(`${t} must be a real file: ${d}`);return{target:p,stat:m}},async hash(d){let p=await f(d);return tx(p,{bigint:!0,label:`${t} ${d}`,verify:async(m,h)=>{if(!wc(i,h.realPath))throw new Error(`${t} resolves outside the project root`);let g=n,v=[n];for(let w of Je.relative(n,Je.dirname(p)).split(Je.sep).filter(Boolean))g=Je.join(g,w),v.push(g);for(let w of v){let y=await o.get(w),R=await Kr.lstat(w,{bigint:!0});if(!R.isDirectory()||R.isSymbolicLink()||c(R)!==c(y.stat))throw new Error(`${t} directory changed while reading: ${Je.relative(n,w)||"."}`)}}})},async read(d,p,m={}){let h=await f(d);return Yo(h,p,{...m,label:`${t} ${d}`,verify:async(g,v)=>{if(!wc(i,v.realPath))throw new Error(`${t} resolves outside the project root`);if(r.deferDirectoryChecks)return;let w=n,y=[n];for(let R of Je.relative(n,Je.dirname(h)).split(Je.sep).filter(Boolean))w=Je.join(w,R),y.push(w);for(let R of y){let N=await o.get(R),b=await Kr.lstat(R,{bigint:!0});if(!b.isDirectory()||b.isSymbolicLink()||c(b)!==c(N.stat))throw new Error(`${t} directory changed while reading: ${Je.relative(n,R)||"."}`)}}})},async finish(d={}){if(a)throw new Error(`${t} read session is already finished`);a=!0;let p=[];for(let[m,h]of o){let g=await h,v=await Kr.lstat(m,{bigint:!0});if(!v.isDirectory()||v.isSymbolicLink()||c(g.stat)!==c(v)||!d.allowDirectoryContentChanges&&s(g.stat)!==s(v)&&(!g.ignoreEntry||await l(m,g.ignoreEntry)!==g.namespace)||await Kr.realpath(m)!==g.real)throw new Error(`${t} directory changed while observing: ${Je.relative(n,m)||"."}`);s(g.stat)!==s(v)&&p.push(Je.relative(n,m).replaceAll("\\","/")||".")}return{changedDirectories:p}}}}function ix(e){let t=e?.code;return t==="ENOENT"||t==="ENOTDIR"}function wc(e,t){let r=Je.relative(e,t);return r===""||!Je.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${Je.sep}`)}async function ck(e,t){let r=Je.resolve(e),n=await ox(r);if(!n.isDirectory()||n.isSymbolicLink())throw new Error(`${t} project root must be a real directory`);return ax(r)}async function sx(e,t,r,n){let i=e;for(let o=0;o<r.length;o++){i=Je.join(i,r[o]);let a;try{a=await ox(i)}catch(l){if(ix(l))return{exists:!1,kind:"missing"};throw l}if(a.isSymbolicLink()){let l=Je.relative(e,i).replaceAll("\\","/");throw new Error(`${n.label} crosses a symbolic link or junction at ${l}`)}let s=o===r.length-1;if(!s&&!a.isDirectory()){let l=Je.relative(e,i).replaceAll("\\","/");throw new Error(`${n.label} ancestor ${l} must be a real directory`)}if(s&&(n.expected==="file"&&!a.isFile()||n.expected==="directory"&&!a.isDirectory()||n.expected==="any"&&!a.isFile()&&!a.isDirectory()))throw new Error(`${n.label} must be a real ${n.expected}`);let c=await ax(i);if(!vQ(t,c))throw new Error(`${n.label} resolves outside the project root`);if(s)return{exists:!0,kind:a.isFile()?"file":a.isDirectory()?"directory":"missing"}}return{exists:!0,kind:"directory"}}async function cx(e,t,r){let n=Jo(t,r.label),i=Je.resolve(e),o=await ck(i,r.label),a=n.split("/"),s=Je.resolve(i,...a);if(!wc(i,s))throw new Error(`${r.label} must stay inside the project root`);let c=await sx(i,o,a,r);return{projectRoot:i,target:s,relative:n,exists:c.exists,kind:c.kind}}async function ie(e,t,r){if(r.expected===void 0)return cx(e,t,r);try{return await wQ(e,t,r.expected)}catch(n){throw n instanceof Error&&n.message.includes("Protected project path")&&(n.message=n.message.replaceAll("Protected project path",r.label)),n}}async function $t(e,t,r){let n=Jo(t,r.label),i=Je.resolve(e),o=await ck(i,r.label),a=n.split("/"),s=i;for(let c of a){s=Je.join(s,c);let l;try{l=await Kr.lstat(s)}catch(d){if(!ix(d))throw d;try{await Kr.mkdir(s)}catch(p){if(p.code!=="EEXIST")throw p}l=await Kr.lstat(s)}let u=Je.relative(i,s).replaceAll("\\","/");if(l.isSymbolicLink())throw new Error(`${r.label} crosses a symbolic link or junction at ${u}`);if(!l.isDirectory())throw new Error(`${r.label} directory ${u} must be a real directory`);let f=await Kr.realpath(s);if(!wc(o,f))throw new Error(`${r.label} resolves outside the project root`)}return await sx(i,o,a,{label:r.label,expected:"directory"}),s}async function lx(e,t,r,n){let i=!n.hooks&&!n.bigint?gQ.getStore():void 0;if(i){let s=Je.resolve(e),c=i.get(s);return c||(c=fm(s,n.label,{deferDirectoryChecks:!0}).catch(l=>{throw i.delete(s),l}),i.set(s,c)),(await c).read(t,r,n)}let o=await fm(e,n.label),a=await o.read(t,r,n);return await o.finish({allowDirectoryContentChanges:!0}),a}async function Qe(e,t,r,n){if(n.hooks||n.bigint)return lx(e,t,r,n);try{return await yQ(e,t,r)}catch(i){throw i instanceof Error&&i.message.includes(sk)&&(i.message=i.message.replaceAll(sk,n.label)),i}}var gQ,ox,ax,vQ,wQ,sk,yQ,lt=x(()=>{"use strict";Xo();eo();Ni();gQ=new hQ;ox=En("protectedChainLstat",e=>Kr.lstat(e)),ax=En("protectedChainRealpath",e=>Kr.realpath(e)),vQ=to("protectedChainInside",wc);wQ=En("protectedInspectPath",(e,t,r)=>cx(e,t,{label:"Protected project path",expected:r}));sk="Cached protected project read",yQ=En("protectedReadFile",(e,t,r)=>lx(e,t,r,{label:sk}))});import{createHash as kQ}from"crypto";function lk(e,t){return e.exists===t.exists&&e.sha256===t.sha256}function bQ(e){let t=e?.code;return t==="ENOENT"||t==="ENOTDIR"}async function pm(e,t={}){return(await ju(e,t)).document}async function ux(e){try{return(await Qe(e,Ou,Iu,{label:Ou})).bytes}catch(t){if(bQ(t))return null;throw t}}function dx(e){return e?{exists:!0,sha256:kQ("sha256").update(e).digest("hex")}:{exists:!1,sha256:null}}async function mm(e){return dx(await ux(e))}async function ju(e,t={}){let r=await ux(e);return{source:r?.toString("utf8")??null,document:r?vc(r.toString("utf8"),t):null,identity:dx(r)}}async function uk(e){return(await pm(e))?.config??null}var Ou,yc=x(()=>{"use strict";eo();lt();Ou=".comet/config.yaml"});import{promises as fk}from"node:fs";async function pk(e,t){let r;for(let n=0;n<=dk.length;n+=1)try{return await e()}catch(i){r=i;let o=i.code;if(n===dk.length||!AQ.has(o??""))throw i;await new Promise(a=>setTimeout(a,dk[n]))}throw r}async function ro(e,t){await pk(()=>fk.rename(e,t),`rename ${t}`)}async function $u(e){await pk(()=>fk.unlink(e),`unlink ${e}`)}async function kc(e,t){await pk(()=>fk.link(e,t),`link ${t}`)}var AQ,dk,Du=x(()=>{"use strict";AQ=new Set(["EPERM","EACCES","EBUSY","ENOTEMPTY"]),dk=[50,100,200]});import{randomUUID as fx}from"crypto";import{constants as RQ,promises as ut}from"fs";import wt from"path";async function mk(e,t){try{return await kc(e,t),{linked:!0}}catch(r){let n=r.code;if(n!=="ENOTSUP"&&n!=="EOPNOTSUPP")throw r}return await ut.copyFile(e,t,RQ.COPYFILE_EXCL),{linked:!1}}function Ma(e,t){let r=wt.relative(e,t);return r===""||!wt.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${wt.sep}`)}function hm(e){return{dev:e.dev,ino:e.ino,birthtime:e.birthtimeMs}}function NQ(e,t){return ot(e,hm(t))}function Va(e,t){return ot(hm(e),hm(t))}function px(e,t){return Va(e,t)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.mtimeMs===t.mtimeMs&&e.size===t.size}async function gm(e){let t=await ut.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 ut.realpath(e),...hm(t)}}async function fr(e){for(let t of e){let r=await ut.lstat(t.path);if(!r.isDirectory()||r.isSymbolicLink()||!NQ(t,r)||await ut.realpath(t.path)!==t.realPath)throw new Error(`Contained atomic write parent changed before commit: ${t.path}`)}}async function SQ(e,t,r){let[n,i]=await Promise.all([ut.lstat(e),ut.realpath(e),fr(r)]);if(!n.isFile()||n.isSymbolicLink()||!Va(n,t)||!Ma(r[0].realPath,i))throw new Error("Contained atomic write temporary file changed after close");return n}async function mx(e,t){let r=await hk(e,t);if(r)return r;let n=wt.resolve(e),i=wt.resolve(t);if(!Ma(n,i))throw new Error(`Contained atomic write parent is outside its managed root: ${t}`);let o=[await gm(n)],a=wt.relative(n,i).split(wt.sep).filter(Boolean),s=n;for(let c of a){await fr(o),s=wt.join(s,c);try{await ut.mkdir(s)}catch(u){if(u.code!=="EEXIST")throw u}let l=await gm(s);if(!Ma(o[0].realPath,l.realPath))throw new Error(`Contained atomic write parent resolves outside its managed root: ${s}`);o.push(l)}return await fr(o),o}async function hk(e,t){let r=wt.resolve(e),n=wt.resolve(t);if(!Ma(r,n))throw new Error(`Contained file parent is outside its managed root: ${t}`);let i=[await gm(r)],o=wt.relative(r,n).split(wt.sep).filter(Boolean),a=r;for(let s of o){a=wt.join(a,s);try{let c=await gm(a);if(!Ma(i[0].realPath,c.realPath))throw new Error(`Contained file parent resolves outside its managed root: ${a}`);i.push(c)}catch(c){if(c.code==="ENOENT")return null;throw c}}return await fr(i),i}async function gk(e){let t;try{t=await ut.open(e,"r"),await t.sync()}catch(r){let n=r.code;if(!["EACCES","EBADF","EINVAL","EISDIR","ENOTSUP","EPERM"].includes(n??""))throw r}finally{await t?.close()}}async function EQ(e,t,r){let n=wt.dirname(e),i=await mx(r.containedRoot,n),o=wt.join(n,`.${wt.basename(e)}.${fx()}.tmp`),a,s,c;try{await r.beforeTemporaryOpen?.(),a=await ut.open(o,"wx"),s=await a.stat();let[l,u]=await Promise.all([ut.lstat(o),ut.realpath(o)]);if(await fr(i),!l.isFile()||l.isSymbolicLink()||!Va(s,l)||!Ma(i[0].realPath,u))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(),c=await a.stat(),!Va(s,c))throw new Error("Contained atomic write temporary file changed while writing");if(await a.close(),a=void 0,await r.afterTemporaryClose?.(),!c)throw new Error("Contained atomic write temporary file was not written");c=await SQ(o,c,i),await r.beforeCommit?.(),await fr(i);let f=await ut.lstat(o);if(!f.isFile()||f.isSymbolicLink()||!c||!px(f,c))throw new Error("Contained atomic write temporary file changed before commit");r.exclusive?(r.requireAtomicPublication?await kc(o,e):await mk(o,e),await ut.unlink(o)):await ro(o,e),await gk(n)}catch(l){await a?.close();try{await fr(i),await ut.rm(o,{force:!0})}catch{}throw l}}async function Dt(e,t,r){await EQ(e,t,r)}async function hx(e,t,r){let n=await hk(r.containedRoot,wt.dirname(e));if(!n)throw Object.assign(new Error("Contained link source directory is missing"),{code:"ENOENT"});let i=await mx(r.containedRoot,wt.dirname(t)),o=await ut.lstat(e);if(!o.isFile()||o.isSymbolicLink())throw new Error("Contained link source must be a regular file");let a=wt.join(wt.dirname(t),`.${wt.basename(t)}.${fx()}.tmp`);try{await fr(n),await fr(i),await kc(e,a),await r.beforeCommit?.(),await fr(n),await fr(i);let s=await ut.lstat(a),c=await ut.lstat(e);if(!s.isFile()||s.isSymbolicLink()||!c.isFile()||c.isSymbolicLink()||!Va(o,c)||!Va(c,s)||o.size!==c.size||o.mtimeMs!==c.mtimeMs)throw new Error("Contained link source changed before publication");let l=await ut.lstat(t).catch(u=>{if(u.code==="ENOENT")return null;throw u});l?.isFile()&&!l.isSymbolicLink()&&Va(c,l)?await $u(a):await ro(a,t),await gk(wt.dirname(t)),await fr(n),await fr(i)}catch(s){try{await fr(i),await ut.unlink(a)}catch{}throw s}}async function Fa(e,t){let r=wt.dirname(e),n=await hk(t.containedRoot,r);if(!n)return!1;let i,o;try{i=await ut.lstat(e),o=await ut.realpath(e)}catch(c){if(c.code==="ENOENT")return!1;throw c}if(!i.isFile()||i.isSymbolicLink()||!Ma(n[0].realPath,o))throw new Error("Contained file removal target must be a regular file inside its managed root");await t.beforeRemove?.(),await fr(n);let[a,s]=await Promise.all([ut.lstat(e),ut.realpath(e)]);if(!a.isFile()||a.isSymbolicLink()||!px(i,a)||s!==o)throw new Error("Contained file removal target changed before removal");return await $u(e),await fr(n),await gk(r),!0}var Yn=x(()=>{"use strict";Du();mc()});var Wte,vk=x(()=>{"use strict";Yn();yc();lt();Wte=Number.MAX_SAFE_INTEGER});async function wk(e,t){if(!t)return;let r=await mm(e);if(!lk(r,t))throw new Error("Project config changed before commit; rerun the operation")}var yk=x(()=>{"use strict";Yn();eo();yc();lt();vk()});import{randomUUID as IQ}from"crypto";import{promises as _r}from"fs";import Xn from"path";function vm(e,t){let r=Xn.relative(e,t);return r===""||!Xn.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${Xn.sep}`)}function xQ(e,t){return ot({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function wm(e,t){return ot({dev:e.dev,ino:e.ino,birthtime:e.birthtimeMs},{dev:t.dev,ino:t.ino,birthtime:t.birthtimeMs})}function PQ(e,t){return wm(e,t)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.mtimeMs===t.mtimeMs&&e.size===t.size}async function gx(e){let t=await _r.lstat(e);if(!t.isDirectory()||t.isSymbolicLink())throw new Error(`Native atomic write parent must be a real directory: ${e}`);return{path:e,realPath:await _r.realpath(e),dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs}}async function bc(e){for(let t of e){let r=await _r.lstat(t.path);if(!r.isDirectory()||r.isSymbolicLink()||!xQ(t,r)||await _r.realpath(t.path)!==t.realPath)throw new Error(`Native atomic write parent changed before commit: ${t.path}`)}}async function TQ(e,t,r){let[n,i]=await Promise.all([_r.lstat(e),_r.realpath(e),r?bc(r):Promise.resolve()]);if(!n.isFile()||n.isSymbolicLink()||!wm(n,t)||r&&!vm(r[0].realPath,i))throw new Error("Native atomic write temporary file changed after close");return n}async function OQ(e,t){let r=Xn.resolve(e),n=Xn.resolve(t);if(!vm(r,n))throw new Error(`Native atomic write parent is outside its managed root: ${t}`);let i=[await gx(r)],o=Xn.relative(r,n).split(Xn.sep).filter(Boolean),a=r;for(let s of o){await bc(i),a=Xn.join(a,s);try{await _r.mkdir(a)}catch(l){if(l.code!=="EEXIST")throw l}let c=await gx(a);if(!vm(i[0].realPath,c.realPath))throw new Error(`Native atomic write parent resolves outside its managed root: ${a}`);i.push(c)}return await bc(i),i}async function Bu(e){let t;try{t=await _r.open(e,"r"),await t.sync()}catch(r){let n=r.code;if(!["EACCES","EBADF","EINVAL","EISDIR","ENOTSUP","EPERM"].includes(n??""))throw r}finally{await t?.close()}}async function vx(e,t,r={}){let n=Xn.dirname(e),i=r.containedRoot?await OQ(r.containedRoot,n):null;i||await _r.mkdir(n,{recursive:!0});let o=Xn.join(n,`.${Xn.basename(e)}.${IQ()}.tmp`),a,s,c;try{if(await r.beforeTemporaryOpen?.(),a=await _r.open(o,"wx"),s=await a.stat(),i){let[l,u]=await Promise.all([_r.lstat(o),_r.realpath(o)]);if(await bc(i),!l.isFile()||l.isSymbolicLink()||!wm(s,l)||!vm(i[0].realPath,u))throw new Error("Native 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(),c=await a.stat(),!wm(s,c))throw new Error("Native atomic write temporary file changed while writing");if(await a.close(),a=void 0,await r.afterTemporaryClose?.(),!c)throw new Error("Native atomic write temporary file was not written");if(c=await TQ(o,c,i),await r.beforeCommit?.(),i){await bc(i);let l=await _r.lstat(o);if(!l.isFile()||l.isSymbolicLink()||!c||!PQ(l,c))throw new Error("Native atomic write temporary file changed before commit")}r.exclusive?(await kc(o,e),await $u(o)):await ro(o,e),await Bu(n)}catch(l){if(await a?.close(),!i)await _r.rm(o,{force:!0});else try{await bc(i),await _r.rm(o,{force:!0})}catch{}throw l}}async function qe(e,t,r={}){await vx(e,t,r)}async function wx(e,t,r={}){await vx(e,t,r)}async function Bt(e,t,r={}){await qe(e,JSON.stringify(t,null,2)+`
|
|
186
|
+
`,r)}var dt=x(()=>{"use strict";Du();hc()});import{createHash as jQ}from"node:crypto";import{lstatSync as Wu,readFileSync as $Q,realpathSync as yx}from"node:fs";import DQ from"node:os";import Ir from"node:path";function kk(e){return`${e.dev}:${e.ino}:${e.birthtimeNs}`}function ym(e){return process.platform==="win32"?yx.native(e):yx(e)}function WQ(e){return BQ(e)}function qQ(e){let t=ym(Ir.resolve(e)),r=Wu(t,{bigint:!0});if(!r.isDirectory())throw new Error(`工作区必须是目录:${e}`);let n=kk(r),i=(c,l)=>({projectRoot:t,workspaceId:jQ("sha256").update(JSON.stringify(["comet.workspace.v2",t,n,c,l])).digest("hex")}),o=Ir.join(t,".git"),a,s;try{let c=Wu(o);if(c.isSymbolicLink())throw new Error(`工作区 .git 不能是符号链接:${o}`);if(c.isDirectory())a=ym(o),s=kk(Wu(a,{bigint:!0}));else if(c.isFile()){let l=/^gitdir: (.+)\r?\n?$/u.exec($Q(o,"utf8"));if(!l)throw new Error(`工作区 .git 文件格式无效:${o}`);a=ym(Ir.resolve(t,l[1].trim()));let u=Wu(a,{bigint:!0});if(!u.isDirectory())throw new Error(`工作区 Git 元数据必须是目录:${a}`);s=kk(u)}else throw new Error(`工作区 .git 类型无效:${o}`)}catch(c){if(c.code!=="ENOENT")throw c;try{Wu(o)}catch(l){if(l.code==="ENOENT")return i(o,null);throw l}throw c}return i(a,s)}function kx(e){let t=Ir.dirname(e);if(t===e)return e;try{return Ir.join(ym(t),Ir.basename(e))}catch(r){if(r.code!=="ENOENT")throw r;return Ir.join(kx(t),Ir.basename(e))}}function bk(e){let t=WQ(e),r=process.env.COMET_DATA_DIR;if(r!==void 0&&(!r.trim()||!Ir.isAbsolute(r)))throw new Error("COMET_DATA_DIR 必须是非空绝对路径");let n=LQ(r??Ir.join(DQ.homedir(),".comet")),i=Ir.relative(t.projectRoot,n);if(i===""||!Ir.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${Ir.sep}`))throw new Error(`用户级 Runtime 数据根不能位于当前工作区内:${n};工作区:${t.projectRoot}`);let o=Ir.join(n,"workspaces",t.workspaceId);return{...t,dataRoot:n,workspaceRoot:o,runtimeRoot:Ir.join(o,"runtime")}}function Le(e){return bk(e).runtimeRoot}var BQ,LQ,Ak=x(()=>{"use strict";Ni();BQ=to("workspaceIdentity",qQ);LQ=to("workspaceRuntimeParent",kx)});import{promises as qu}from"node:fs";import bx from"node:path";async function Ha(e){return Le(e)}async function Rk(e){return[Le(e)]}async function Ax(e){let t=bx.dirname(e);if(t!==e){await Ax(t);try{await qu.mkdir(e,{mode:448})}catch(n){if(n.code!=="EEXIST")throw n}}let r=await qu.lstat(e);if(!r.isDirectory()||r.isSymbolicLink())throw new Error("Runtime 路径必须是真实目录:"+e)}async function Cn(e){let t=Le(e);return await Ax(t),t}async function Nk(e,t,r){try{let n=await qu.lstat(e);if(n.isSymbolicLink())throw new Error("旧 Runtime 路径不能是符号链接:"+e);let i=n.isDirectory()?bx.join(e,".comet-runtime-migration.json"):e,o=await qu.lstat(i);if(!o.isFile()||o.isSymbolicLink())return!1;let a;try{a=JSON.parse((await Yo(i,Number.MAX_SAFE_INTEGER,{label:"旧 Runtime 标记"})).bytes.toString("utf8"))}catch(s){if(s instanceof SyntaxError)return!1;throw s}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:!n.isDirectory()||(await qu.readdir(e)).every(s=>s===".comet-runtime-migration.json")}catch(n){if(n.code==="ENOENT")return!1;throw n}}var or=x(()=>{"use strict";Ak();Xo()});import{promises as Ac}from"fs";import Ge from"path";import VQ from"os";async function Sk(e){try{return await Ac.lstat(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function FQ(e){try{let t=await Ac.readFile(e,"utf8");return/^schema:\s*comet\.project\.v1\s*$/mu.test(t)}catch(t){if(t.code==="ENOENT")return!1;throw t}}function Lu(e,t){let r=Ge.relative(e,t);return r===""||!Ge.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${Ge.sep}`)}async function Vu(e){let t=[],r=e;for(;!await Sk(r);){let i=Ge.dirname(r);if(i===r)break;t.push(Ge.basename(r)),r=i}let n=await Ac.realpath(r);return Ge.resolve(n,...t.reverse())}async function Ek(e){try{return(await Ac.lstat(e)).isSymbolicLink()}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function Ck(e){let t=Ge.resolve(e);try{(await Ac.stat(t)).isDirectory()||(t=Ge.dirname(t))}catch(i){if(i.code!=="ENOENT")throw i}let r=t,n=Ge.resolve(VQ.homedir());for(;;){if(!(t===n&&r!==n)){let a=Ge.join(t,...km.split("/")),s=t===r||await FQ(a);if(await Sk(a)&&s)return t}if(await Sk(Ge.join(t,".git")))return t;let o=Ge.dirname(t);if(o===t)return r;t=o}}function bm(e){return gc(e)}async function HQ(e,t){let r=bm(t),n=Ge.resolve(e,...r.split("/")),i=await Ac.realpath(e),o=await Vu(n);if(!Lu(i,o))throw new Error("native.artifact_root resolves outside the project root");return n}async function we(e,t,r={}){let n=bm(t),i=await HQ(e,n),o=Ge.join(i,"comet");if(await Ek(o))throw new Error("The configured Native comet root must not be a symbolic link");let[a,s]=await Promise.all([Vu(i),Vu(o)]);if(!Lu(a,s))throw new Error("The configured Native comet root resolves outside its artifact root");let c=Ge.resolve(e),l=Le(c),u=Ge.join(l,"native");if(await Ek(u))throw new Error("The Native Runtime root must not be a symbolic link");return await ft(l,u),{projectRoot:c,configFile:Ge.join(e,...km.split("/")),artifactRoot:i,artifactRootRef:n,nativeRoot:o,specsDir:Ge.join(o,"specs"),changesDir:Ge.join(o,"changes"),archiveDir:Ge.join(o,"archive"),workspaceRuntimeRoot:l,runtimeDir:u,changesRuntimeDir:Ge.join(u,"changes"),transactionsDir:Ge.join(u,"transactions")}}function Rx(e){if(!MQ.test(e))throw new Error(`Invalid Native change name: ${e}`)}function Rc(e,t){Rx(t);let r=Ge.join(e.changesRuntimeDir,t);if(!yt(e.changesRuntimeDir,r))throw new Error("Native change Runtime path escaped");return r}function Nx(e,t){Rx(t);let r=Ge.join(e.changesDir,t,"runtime");if(!yt(e.changesDir,r))throw new Error("Legacy Native change Runtime path escaped");return r}function hn(e,t){return Rc(e,t)}function Ve(e,t){let r=Ge.resolve(t);if(yt(e.runtimeDir,r))return e.runtimeDir;if(yt(e.nativeRoot,r))return e.nativeRoot;throw new Error(`Path is outside Native document and Runtime roots: ${t}`)}function yt(e,t){return Lu(Ge.resolve(e),Ge.resolve(t))}async function ft(e,t){let r=Ge.resolve(e),n=Ge.resolve(t);if(!Lu(r,n))throw new Error(`Path is outside the Native root: ${t}`);if(await Ek(r))throw new Error(`Native root must not be a symbolic link: ${e}`);let[i,o]=await Promise.all([Vu(r),Vu(n)]);if(!Lu(i,o))throw new Error(`Path resolves outside the Native root: ${t}`);return n}var km,MQ,He=x(()=>{"use strict";or();eo();km=".comet/config.yaml",MQ=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u});import QQ from"path";async function Te(e){let t=(await pm(e))?.config??null;return t?.native?t:null}async function Nc(e){let t=await Te(e);if(t?.native.pending_root_move)throw new Error(`Native root move ${t.native.pending_root_move.id} is incomplete; use comet native doctor --repair`)}async function no(e,t,r={}){let n=await ju(e,{allowPartialProject:!0}),i=Tu(n.document?.value??{},t),o=QQ.join(e,...km.split("/"));await qe(o,Pu(i,t.native.language==="zh-CN"?"zh-CN":"en"),{containedRoot:e,beforeCommit:async()=>{await r.beforeCommit?.(),await wk(e,n.identity)}})}var Mu,Et=x(()=>{"use strict";eo();yc();yk();dt();He();Mu=cm});function UQ(e){if(!Number.isSafeInteger(e)||e<0)throw new Error("Native portable text byte budget must be a non-negative safe integer")}function Ct(e,t=16384){if(typeof e!="string")throw new Error("Native portable text must be a string");if(UQ(t),Buffer.byteLength(e,"utf8")<=t)return{text:e,truncated:!1};let r="",n=0;for(let i of e){let o=Buffer.byteLength(i,"utf8");if(n+o>t)break;r+=i,n+=o}return{text:r,truncated:!0}}var io=x(()=>{"use strict"});function Qa(e,t,r,n=""){let i=Object.keys(e),o=t.filter(s=>!Object.hasOwn(e,s)),a=i.filter(s=>!t.includes(s));if(o.length||a.length)throw new Fu({code:"invalid-fields",path:n,context:r,missingFields:o,unknownFields:a,expectedFields:[...t]})}var Fu,Am=x(()=>{"use strict";Fu=class extends Error{issues;constructor(t){let r=[t.missingFields.length?`missing: ${t.missingFields.join(", ")}`:"",t.unknownFields.length?`unknown: ${t.unknownFields.join(", ")}`:""].filter(Boolean).join("; ");super(`${t.context} fields are invalid at ${t.path||"/"} (${r})`),this.name="NativeInputValidationError",this.issues=[t]}}});function Sc(e,t,r){if(typeof e!="string"||!t.includes(e))throw new Error(`${r} must be one of: ${t.join(", ")}`);return e}function Si(e){return`<${e.join("|")}>`}var Hu,Ua,Qu,Rm,Uu,Ex,Ja=x(()=>{"use strict";Hu=["passed","failed","not-run"],Ua=["pass","fail","blocked"],Qu=["passed","failed","blocked"],Rm=["aligned","conflict","blocked"],Uu=["implemented-with-evidence","implemented-no-evidence","not-implemented","known-fail"],Ex=["final-result"]});function _k(e,t){if(typeof e!="string"||!e.trim()||e.length>4e3||/^<[^>]+>$/u.test(e.trim()))throw new Error(`${t} must contain a concrete statement of at most 4000 characters`);return e.trim()}function Nm(e,t,r="acceptance_review"){if(!Array.isArray(e))throw new Error(`Native Builder ${r} must be an array`);let n=[],i=l=>{try{return l()}catch(u){n.push(u instanceof Error?u.message:String(u))}},o=t&&new Set(t.map(({id:l})=>l)),a=[],s=[],c=e.flatMap((l,u)=>{let f=`Native Builder ${r}[${u}]`;if(!l||typeof l!="object"||Array.isArray(l))return n.push(`${f} must be an object`),[];let d=l;i(()=>Qa(d,["id","status","evidence","note"],f,`/${r}/${u}`));let p=i(()=>_k(d.id,`${f}.id`));p&&(a.includes(p)&&n.push(`${f}.id contains duplicate ID: ${p}`),a.push(p),o&&!o.has(p)&&s.push({index:u,id:p}));let m=p&&o?.has(p)?f+" ("+p+")":f,h=i(()=>Sc(d.status,Uu,`${f}.status`)),g;Array.isArray(d.evidence)?g=d.evidence.map((w,y)=>i(()=>_k(w,`${f}.evidence[${y}]`))).filter(w=>w!==void 0):n.push(`${m}.evidence must be an array of concrete strings of at most 4000 characters; received ${typeof d.evidence}`);let v=i(()=>_k(d.note,`${m}.note`));return p&&h&&g&&v?[{id:p,status:h,evidence:g,note:v}]:[]});if(t&&!n.length)return Ju(t,c),c;if(t){for(let{index:u,id:f}of s)n.push(`Native Builder ${r}[${u}].id contains unknown ID: ${f}`);let l=t.filter(({id:u})=>!a.includes(u)).map(({id:u})=>u);l.length&&n.push(`Native Builder ${r} missing: ${l.join(", ")}`)}if(n.length)throw new Error(n.join(`
|
|
187
|
+
`));return c}function Ju(e,t){if(!t)throw new Zo(e.map(({id:c})=>c),[]);let r=new Set(e.map(({id:c})=>c)),n=t.map(({id:c})=>c),i=new Set(n);if(i.size!==n.length)throw new Error("Native Builder acceptance_review contains duplicate IDs");let o=n.filter(c=>!r.has(c));if(o.length)throw new Error(`Native Builder acceptance_review contains unknown IDs: ${o.join(", ")}`);let a=e.filter(({id:c})=>!i.has(c)).map(({id:c})=>c),s=t.filter(c=>c.status!=="implemented-with-evidence"||c.evidence.length===0).map(({id:c})=>c);if(a.length||s.length)throw new Zo(a,s)}var Zo,Sm=x(()=>{"use strict";Am();Ja();Zo=class extends Error{constructor(r,n){super(`Native Builder handoff is incomplete${r.length?`; missing: ${r.join(", ")}`:""}${n.length?`; not ready: ${n.join(", ")}`:""}. Complete acceptance_review for every requirement and its evidence before Verify`);this.missingIds=r;this.incompleteIds=n}missingIds;incompleteIds}});var Cx,A,_n=x(()=>{"use strict";Cx=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"}),A=class extends Error{constructor(r,n){super(`${r}: ${n}`);this.code=r;this.name="RuntimeProtocolError",this.recovery=Object.hasOwn(Cx,r)?Cx[r]:"manual-review"}code;recovery}});import{createHash as JQ}from"node:crypto";import{types as zQ}from"node:util";function In(e){return Ik.has(e)}function Em(e,t=!0,r=!1,n=!1){let i=new Set,o=new WeakMap;function a(s,c){if(c>64)throw new A("INVALID_JSON","数据嵌套超过 64 层");if(s===null||typeof s=="string"||typeof s=="boolean")return r?JSON.stringify(s):s;if(typeof s=="number"&&Number.isFinite(s))return r?JSON.stringify(s):s===0?0:s;if(typeof s!="object"||s===null)throw new A("INVALID_JSON","数据必须能无损保存为 JSON");if(i.has(s))throw new A("INVALID_JSON","数据包含循环引用");if(zQ.isProxy(s))throw new A("INVALID_JSON","仅接受无执行行为的 JSON 数据");let l=Ik.get(s);if(!t&&!r&&l!==void 0){if(c+l>64)throw new A("INVALID_JSON","数据嵌套超过 64 层");return o.set(s,{value:s,height:l}),s}let u=o.get(s);if(u){if(c+u.height>64)throw new A("INVALID_JSON","数据嵌套超过 64 层");return t?Ye(u.value):r?u.value:s}i.add(s);let f=0,d=m=>m&&typeof m=="object"?o.get(m)?.height??0:0,p=m=>(o.set(s,{value:m,height:f}),n&&(Object.freeze(s),Ik.set(s,f)),m);try{if(Array.isArray(s)){if(Reflect.ownKeys(s).length!==s.length+1)throw new A("INVALID_JSON","数组不能包含空洞或额外属性");let v=[];for(let w=0;w<s.length;w+=1){let y=Object.getOwnPropertyDescriptor(s,String(w));if(!y||!("value"in y))throw new A("INVALID_JSON","数组元素必须是普通数据");let R=a(y.value,c+1);f=Math.max(f,1+d(y.value)),(t||r)&&v.push(R)}return p(r?`[${v.join(",")}]`:t?v:s)}let m=Object.getPrototypeOf(s);if(m!==Object.prototype&&m!==null)throw new A("INVALID_JSON","仅接受普通 JSON 对象");let h=[],g=Reflect.ownKeys(s);(t||r)&&g.sort((v,w)=>{let y=String(v),R=String(w),N=String(Number(y))===y&&Number.isInteger(Number(y))&&Number(y)>=0&&Number(y)<4294967295,b=String(Number(R))===R&&Number.isInteger(Number(R))&&Number(R)>=0&&Number(R)<4294967295;return N||b?N&&b?Number(y)-Number(R):N?-1:1:y<R?-1:y>R?1:0});for(let v of g){let w=Object.getOwnPropertyDescriptor(s,v);if(typeof v!="string"||!w.enumerable||!("value"in w))throw new A("INVALID_JSON","对象属性必须是可枚举的字符串数据属性");let y=a(w.value,c+1);f=Math.max(f,1+d(w.value)),(t||r)&&h.push([v,y])}return p(r?`{${h.map(([v,w])=>`${JSON.stringify(v)}:${w}`).join(",")}}`:t?Object.fromEntries(h):s)}finally{i.delete(s)}}return a(e,0)}function Ei(e){return Em(e,!1,!0)}function pt(e){return Em(e)}function Ye(e){if(e===null||typeof e!="object")return e;if(Array.isArray(e)){let r=[];for(let n=0;n<e.length;n++)r.push(Ye(e[n]));return r}let t={};for(let r of Object.keys(e)){let n=Ye(e[r]);r==="__proto__"?Object.defineProperty(t,r,{value:n,enumerable:!0,writable:!0,configurable:!0}):t[r]=n}return t}function xn(e){Em(e,!1)}function D(e){let t=e!==null&&typeof e=="object"&&In(e),r=t?_x.get(e):void 0;if(r!==void 0)return r;let n=JQ("sha256").update(Ei(e)).digest("hex");return t&&_x.set(e,n),n}function za(e){return Em(e,!1,!1,!0),e}var Ik,_x,xr=x(()=>{"use strict";_n();Ik=new WeakMap,_x=new WeakMap});function Ut(e,t){if(typeof e!="string"||!e.trim()||e.length>4096)throw new A("INVALID_ACTION",`${t} 必须是非空字符串且不超过 4096 字符`)}function Ci(e){return In(e)?{...e,reconciliations:[...e.reconciliations]}:structuredClone(e)}function xk(e,t,r){if(t!==e.attempt||r!==e.inputHash)throw new A("STALE_ACTION","执行尝试或输入版本与当前 Action 不一致")}function Pk(e){return["succeeded","failed","cancelled"].includes(e.status)}function Ix(e){return xx(e,e.input)}function xx(e,t,r){for(let a of["id","runId","stepId","type"])Ut(e[a],a);e.ref!==void 0&&Ut(e.ref,"ref");let n=e.attempt??1;if(!Number.isSafeInteger(n)||n<1)throw new A("INVALID_ACTION","attempt 必须是正安全整数");let i=e.retry??"manual";if(!["idempotent","reconcile","manual"].includes(i))throw new A("INVALID_ACTION","retry 策略无效");let o=e.requiredCapabilities??[];for(let a of o)Ut(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:n,input:t,inputHash:r??D(t),status:"pending",retry:i,requiredCapabilities:[...new Set(o)],receipts:[],reconciliations:[]}}function Tk(e,t){xk(e,t.attempt,t.inputHash),Ut(t.executorId,"executorId"),Ut(t.token,"token"),t.sessionId!==void 0&&Ut(t.sessionId,"sessionId");let r={executorId:t.executorId,token:t.token,...t.sessionId===void 0?{}:{sessionId:t.sessionId}};if(e.claim){if(D(e.claim)===D(r)&&e.status==="running")return Ci(e);throw new A("ACTION_ALREADY_CLAIMED","Action 已由执行者领取,不能替换其归属")}if(e.status!=="pending")throw new A("ACTION_NOT_PENDING","只有待执行 Action 可以被领取");return{...Ci(e),claim:r,status:"running",...t.executionOrigin?{executionOrigin:structuredClone(t.executionOrigin)}:{}}}function Cm(e,t){if(t=Im(t),Ut(t.outcomeId,"outcomeId"),!["succeeded","failed"].includes(t.status))throw new A("INVALID_OUTCOME","结果必须声明执行成功或失败");t.event!==void 0&&Ut(t.event,"event");let r=D(t),n=e.rejectedOutcomes?.find(o=>o.outcome.outcomeId===t.outcomeId);if(n)throw D(n.outcome)!==r?new A("OUTCOME_CONFLICT","同一结果标识不能提交不同内容;修正后请使用新的 outcomeId,并保留原 actionId、attempt、inputHash 和 claimToken"):new A(n.code,n.reason);let i=e.receipts.find(o=>o.outcomeId===t.outcomeId);if(i){if(i.hash!==r)throw new A("OUTCOME_CONFLICT","同一结果标识不能提交不同内容;修正后请使用新的 outcomeId,并保留原 actionId、attempt、inputHash 和 claimToken");return{action:Ci(e),duplicate:!0}}if(xk(e,t.attempt,t.inputHash),t.actionId!==e.id)throw new A("STALE_ACTION","结果不属于当前 Action");if(Pk(e))throw new A("ACTION_TERMINAL","Action 已终止,不能接受新结果");if(!e.claim||!["running","unknown"].includes(e.status))throw new A("ACTION_NOT_RUNNING","Action 尚未交给执行者");if(t.claimToken!==e.claim.token)throw new A("STALE_ACTION","结果不属于当前执行者的领取记录");for(let o of t.artifacts??[])if(Ut(o.uri,"artifact.uri"),!/^[a-f0-9]{64}$/.test(o.sha256))throw new A("INVALID_OUTCOME","产物引用必须包含 SHA-256");return{action:{...Ci(e),status:t.status,outcome:structuredClone(t),receipts:[...e.receipts,{outcomeId:t.outcomeId,hash:r}]},duplicate:!1}}function Px(e,t){if(Ut(t,"reason"),!["running","unknown"].includes(e.status))throw new A("ACTION_NOT_RUNNING","只有已派发 Action 才存在执行结果不明的情况");return{...Ci(e),status:"unknown",reason:t}}function Tx(e,t){if(e.rejectedOutcomes?.some(n=>n.outcome.attempt===e.attempt))throw new A("OUTCOME_ALREADY_RECORDED","当前执行尝试已记录结果,不能声明未执行并重试;请核对并修正同一次结果");if(!["failed","unknown"].includes(e.status))throw new A("ACTION_ACTIVE","仅失败或待核对的 Action 可以重试");if((e.retry!=="idempotent"||e.status==="unknown")&&!t)throw new A("RECONCILIATION_REQUIRED","先核对外部执行结果;不能把断连当作未执行");let r=Ci(e);if(t){if(t.resolution!=="not-executed"||t.evidence===null)throw new A("RECONCILIATION_REQUIRED","需要明确的未执行结论与核对证据");r.reconciliations.push({attempt:e.attempt,resolution:"not-executed",evidence:pt(t.evidence)})}if(!Number.isSafeInteger(e.attempt+1))throw new A("INVALID_ACTION","执行尝试次数溢出");return r.attempt+=1,r.status="pending",delete r.claim,delete r.executionOrigin,delete r.executionStop,delete r.cancellation,delete r.outcome,delete r.reason,r}function _m(e,t){return Ut(t,"reason"),Pk(e)?Ci(e):{...Ci(e),status:"cancelled",reason:t}}function Ox(e,t){Zn(t,["actionId","attempt","inputHash","claimToken","evidence"]);for(let r of["actionId","inputHash","claimToken","evidence"])Ut(t[r],r);if(!Number.isSafeInteger(t.attempt)||t.attempt<1||/^<.*>$/su.test(t.evidence.trim()))throw new A("INVALID_ACTION","停止确认需要原执行尝试和实际停止证据");if(xk(e,t.attempt,t.inputHash),t.actionId!==e.id||!e.claim||t.claimToken!==e.claim.token)throw new A("STALE_ACTION","停止确认必须绑定原 Action 和领取身份")}function Ok(e,t){if(Ox(e,t),e.status!=="cancelled")throw new A("ACTION_TERMINAL","只能确认已取消 Action 的执行停止");if(e.cancellation&&D(e.cancellation)!==D(t))throw new A("OUTCOME_CONFLICT","当前执行已有不同的停止确认");return{...Ci(e),cancellation:structuredClone(t)}}function jk(e,t){if(Ox(e,t),!Pk(e))throw new A("ACTION_TERMINAL","只能确认终态 Action 的执行停止");if(e.executionStop&&D(e.executionStop)!==D(t))throw new A("OUTCOME_CONFLICT","当前执行已有不同的停止确认");return{...Ci(e),executionStop:structuredClone(t)}}function Zn(e,t,r="INVALID_ACTION"){if(!e||typeof e!="object"||Array.isArray(e)||Object.keys(e).some(n=>!t.includes(n)))throw new A(r,"执行记录包含无效结构或未知字段")}function Im(e){let t=pt(e),r=["actionId","attempt","inputHash","claimToken","outcomeId","status","output"];if(Zn(t,[...r,"artifacts","summary","event"],"INVALID_OUTCOME"),r.some(n=>!Object.hasOwn(t,n)))throw new A("INVALID_OUTCOME","执行结果缺少身份、绑定或 output 字段");for(let n of["actionId","inputHash","claimToken","outcomeId"])if(typeof t[n]!="string"||!t[n].trim()||t[n].length>4096)throw new A("INVALID_OUTCOME",`${n} 必须是非空字符串`);if(typeof t.attempt!="number"||!Number.isSafeInteger(t.attempt)||t.attempt<1)throw new A("INVALID_OUTCOME","attempt 必须是正安全整数");if(t.status!=="succeeded"&&t.status!=="failed")throw new A("INVALID_OUTCOME","status 必须是 succeeded 或 failed");for(let n of["summary","event"])if(t[n]!==void 0&&(typeof t[n]!="string"||!t[n].trim()||t[n].length>4096))throw new A("INVALID_OUTCOME",`${n} 必须是非空字符串`);if(t.artifacts!==void 0){if(!Array.isArray(t.artifacts))throw new A("INVALID_OUTCOME","产物引用必须是数组");for(let n of t.artifacts)if(Zn(n,["uri","sha256"],"INVALID_OUTCOME"),typeof n.uri!="string"||!n.uri.trim()||typeof n.sha256!="string"||!/^[a-f0-9]{64}$/.test(n.sha256))throw new A("INVALID_OUTCOME","产物引用必须包含 URI 与 SHA-256")}return t}function jx(e){return $k(pt(e))}function $k(e,t){if(Zn(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 A("UNSUPPORTED_PROTOCOL","当前 Runtime 不支持此 Action 协议版本");if(!Array.isArray(e.requiredCapabilities)||!Array.isArray(e.receipts)||!Array.isArray(e.reconciliations))throw new A("INVALID_ACTION","Action 缺少能力、结果或核对记录");let r=e,n=xx(r,r.input,t);if(r.inputHash!==n.inputHash||r.retry!==n.retry||r.attempt!==n.attempt)throw new A("INVALID_ACTION","Action 输入绑定或执行参数不完整");if(!["pending","running","unknown","succeeded","failed","cancelled"].includes(r.status))throw new A("INVALID_ACTION","Action 状态无效");if(r.reason!==void 0&&Ut(r.reason,"reason"),r.claim!==void 0&&(Zn(r.claim,["executorId","sessionId","token"]),Ut(r.claim.executorId,"executorId"),Ut(r.claim.token,"token"),r.claim.sessionId!==void 0&&Ut(r.claim.sessionId,"sessionId")),r.status==="pending"&&r.claim||["running","unknown","succeeded","failed"].includes(r.status)&&!r.claim)throw new A("INVALID_ACTION","Action 状态与执行归属不一致");if(r.executionOrigin!==void 0&&(Zn(r.executionOrigin,["workflow"]),Zn(r.executionOrigin.workflow,["id","version","hash"]),Ut(r.executionOrigin.workflow.id,"executionOrigin.workflow.id"),Ut(r.executionOrigin.workflow.version,"executionOrigin.workflow.version"),!r.claim||!/^[a-f0-9]{64}$/u.test(r.executionOrigin.workflow.hash)))throw new A("INVALID_ACTION","执行来源必须包含领取记录和有效工作流摘要");r.cancellation!==void 0&&Ok({...r,input:null},r.cancellation),r.executionStop!==void 0&&jk({...r,input:null},r.executionStop);let i=new Set;for(let a of r.receipts){if(Zn(a,["outcomeId","hash"]),Ut(a.outcomeId,"outcomeId"),!/^[a-f0-9]{64}$/.test(a.hash)||i.has(a.outcomeId))throw new A("INVALID_ACTION","结果记录的标识或摘要无效");i.add(a.outcomeId)}if(r.rejectedOutcomes!==void 0){if(!Array.isArray(r.rejectedOutcomes))throw new A("INVALID_ACTION","Action 的拒绝结果记录必须是数组");let a=new Set;for(let s of r.rejectedOutcomes){if(Zn(s,["outcome","code","reason"]),!["OUTPUT_INVALID","OUTCOME_REJECTED","OUTCOME_PROCESSING_ERROR"].includes(s.code))throw new A("INVALID_ACTION","Action 的拒绝结果代码无效");if(typeof s.reason!="string"||!s.reason.trim())throw new A("INVALID_ACTION","Action 的拒绝结果缺少原因");let c=Im(s.outcome),l=r.receipts.find(u=>u.outcomeId===c.outcomeId);if(a.has(c.outcomeId)||!l||l.hash!==D(c)||c.actionId!==r.id||c.inputHash!==r.inputHash||c.attempt>r.attempt||c.attempt===r.attempt&&r.claim?.token!==c.claimToken)throw new A("INVALID_ACTION","Action 的拒绝结果与当前执行记录不一致");a.add(c.outcomeId)}}let o=new Set;for(let a of r.reconciliations){if(Zn(a,["attempt","resolution","evidence"]),!Number.isSafeInteger(a.attempt)||a.attempt<1||a.attempt>=r.attempt||o.has(a.attempt)||a.resolution!=="not-executed"||a.evidence===null||a.evidence===void 0)throw new A("INVALID_ACTION","核对记录与执行尝试不一致");o.add(a.attempt)}if(r.status==="succeeded"||r.status==="failed"){if(Zn(r.outcome,["actionId","attempt","inputHash","claimToken","outcomeId","status","output","artifacts","summary","event"]),r.outcome.status!==r.status||r.outcome.output===void 0)throw new A("INVALID_ACTION","终态 Action 缺少匹配的结果");let a=r.receipts.find(s=>s.outcomeId===r.outcome.outcomeId);if(!a||a.hash!==D(r.outcome))throw new A("INVALID_ACTION","终态结果与已接受摘要不一致");Cm({...r,input:null,status:"running",receipts:[]},r.outcome)}else if(r.outcome!==void 0)throw new A("INVALID_ACTION","非执行终态不能保存当前执行结果");return r}var Ka=x(()=>{"use strict";_n();xr()});import{types as KQ}from"node:util";import{createHash as GQ}from"node:crypto";function Bx(e,t){let r=e!==null&&typeof e=="object"&&t?.(e);if(r){let i=Dx.get(e);if(i!==void 0)return i}let n=JSON.stringify(e);return r&&n.length<=64*1024&&Dx.set(e,n),n}function YQ(e,t,r){let n=new WeakMap,i=v=>{let w=n.get(v);if(w)return w;let y=Array.isArray(v)?[...v]:{...v};return n.set(v,y),y},o=i(e),a=[],s=[],c=[],l=new Map,u=new Map,f=new WeakMap,d=new Map,p=new Map,m=new Map,h=v=>{let w=v&&typeof v=="object"?f.get(v):void 0;if(w!==void 0)return w;let y=Bx(v,r);return w=l.get(y),w===void 0&&(w=a.length,a.push(v),l.set(y,w)),v&&typeof v=="object"&&f.set(v,w),w},g=v=>{let w=m.get(v);if(w!==void 0)return w;let y=v.base===void 0?void 0:g(v.base),R=s.length;return s.push({...y===void 0?{}:{base:y},entries:v.entries.map(([N,b])=>[N,h(b)]),removed:[...v.removed]}),m.set(v,R),R};for(let v of t){let w=o,y=e;for(let W of v.path.slice(0,-1)){y=y[W];let F=i(y);Object.defineProperty(w,W,{value:F,enumerable:!0,writable:!0,configurable:!0}),w=F}let R=v.path.at(-1),N=w[R];if(!N||typeof N!="object"||Array.isArray(N))continue;if(r?.(N)){let W=$x.get(N);if(!W){let F=N,G=p.get(v.group),Z=Object.entries(F),Ae=G?Z.filter(([rr,q])=>!Object.hasOwn(G.source,rr)||h(G.source[rr])!==h(q)):Z,re=G?Object.keys(G.source).filter(rr=>!Object.hasOwn(F,rr)):[],nt=G&&Ae.length+re.length<Z.length;W={...nt?{base:G.node}:{},entries:nt?Ae:Z,removed:nt?re:[]},$x.set(N,W)}p.set(v.group,{source:N,node:W}),c.push({path:v.path,map:g(W)}),Object.defineProperty(w,R,{value:{},enumerable:!0,writable:!0,configurable:!0});continue}let b=new Map;for(let[W,F]of Object.entries(N)){let G=F&&typeof F=="object"?f.get(F):void 0;if(G===void 0){let Z=Bx(F,r);G=l.get(Z),G===void 0&&(G=a.length,a.push(F),l.set(Z,G)),F&&typeof F=="object"&&f.set(F,G)}b.set(W,G)}let E=JSON.stringify([...b]),I=u.get(E);if(I===void 0){let W=d.get(v.group),F=[...b].filter(([Ae,re])=>W?.entries.get(Ae)!==re),G=W?[...W.entries.keys()].filter(Ae=>!b.has(Ae)):[],Z=W&&F.length+G.length<b.size;I=s.length,s.push({...Z?{base:W.id}:{},entries:Z?F:[...b],removed:Z?G:[]}),u.set(E,I)}d.set(v.group,{id:I,entries:b}),c.push({path:v.path,map:I}),Object.defineProperty(w,R,{value:{},enumerable:!0,writable:!0,configurable:!0})}return c.length?{record:o,pool:{version:1,values:a,maps:s,bindings:c}}:{record:o}}function XQ(){let e=[],t=o=>o===null?0:e[o].height,r=(o,a,s,c)=>{let l=e.length;return e.push({key:o,value:a,left:s,right:c,height:1+Math.max(t(s),t(c))}),l},n=(o,a,s,c)=>{if(t(s)>t(c)+1){let l=e[s];if(t(l.left)>=t(l.right))return r(l.key,l.value,l.left,r(o,a,l.right,c));let u=e[l.right];return r(u.key,u.value,r(l.key,l.value,l.left,u.left),r(o,a,u.right,c))}if(t(c)>t(s)+1){let l=e[c];if(t(l.right)>=t(l.left))return r(l.key,l.value,r(o,a,s,l.left),l.right);let u=e[l.left];return r(u.key,u.value,r(o,a,s,u.left),r(l.key,l.value,u.right,l.right))}return r(o,a,s,c)},i=(o,a,s)=>{if(o===null)return s===void 0?null:r(a,s,null,null);let c=e[o];if(a<c.key){let u=i(c.left,a,s);return u===c.left?o:n(c.key,c.value,u,c.right)}if(a>c.key){let u=i(c.right,a,s);return u===c.right?o:n(c.key,c.value,c.left,u)}if(s!==void 0)return s===c.value?o:r(a,s,c.left,c.right);if(c.left===null)return c.right;if(c.right===null)return c.left;let l=e[c.right];for(;l.left!==null;)l=e[l.left];return n(l.key,l.value,c.left,i(c.right,l.key,void 0))};return{nodes:e,set:i}}function qx(e){let{nodes:t,set:r}=XQ(),n=[];for(let c of e.maps){let l=c.base===void 0?null:n[c.base];for(let u of c.removed)l=r(l,u,void 0);for(let[u,f]of c.entries)l=r(l,u,f);n.push(l)}let i=[],o=new Map,a=c=>{if(c===null)return null;let l=o.get(c);if(l!==void 0)return l;let u=t[c],f=a(u.left),d=a(u.right),p=i.length;return i.push({...u,left:f,right:d}),o.set(c,p),p},s=n.map(a);return{version:3,values:e.values,nodes:i,maps:s,bindings:e.bindings}}function Lx(e,t,r){let n=YQ(e,t,r);return{record:n.record,...n.pool?{pool:qx(n.pool)}:{}}}function*xm(e,t=e.root){if(t===null)return;let r=e.pool.nodes[t];yield*xm(e,r.left),yield[r.key,e.pool.values[r.value]],yield*xm(e,r.right)}function ZQ(e){let t=n=>{let i=e.root;for(;i!==null;){let o=e.pool.nodes[i];if(n===o.key)return o.value;i=n<o.key?o.left:o.right}},r=new Proxy({},{ownKeys:()=>[...xm(e)].map(([n])=>n),get:(n,i)=>typeof i=="string"?e.pool.values[t(i)??-1]:void 0,has:(n,i)=>typeof i=="string"&&t(i)!==void 0,getOwnPropertyDescriptor:(n,i)=>typeof i=="string"&&t(i)!==void 0?{value:e.pool.values[t(i)],enumerable:!0,configurable:!0,writable:!1}:void 0,set:()=>!1,deleteProperty:()=>!1,defineProperty:()=>!1});return oo.set(r,e),r}function Vx(e){let t=e;if(!t||!Array.isArray(t.values)||!Array.isArray(t.maps)||!Array.isArray(t.bindings))return Rt("JSON 引用池格式无效");if(e.version===1){let i=e;return Object.keys(i).some(o=>!["version","values","maps","bindings"].includes(o))&&Rt("JSON 引用池字段无效"),i.maps.forEach((o,a)=>{(!o||!Array.isArray(o.entries)||!Array.isArray(o.removed)||o.base!==void 0&&!Ec(o.base,a)||Object.keys(o).some(c=>!["base","entries","removed"].includes(c)))&&Rt("JSON 映射引用无效");let s=new Set;for(let c of o.removed)(typeof c!="string"||s.has(c))&&Rt("JSON 删除键无效"),s.add(c);for(let c of o.entries)(!Array.isArray(c)||c.length!==2||typeof c[0]!="string"||!Ec(c[1],i.values.length)||s.has(c[0]))&&Rt("JSON 值引用无效"),s.add(c[0])}),Vx(qx(i))}let r=e;if(r.version!==3||!Array.isArray(r.nodes)||Object.keys(r).some(i=>!["version","values","maps","bindings","nodes"].includes(i)))return Rt("JSON 引用池版本或字段无效");let n=[];return r.nodes.forEach((i,o)=>{(!i||typeof i.key!="string"||!Ec(i.value,r.values.length)||![i.left,i.right].every(c=>c===null||Ec(c,o))||Object.keys(i).some(c=>!["key","value","left","right","height"].includes(c)))&&Rt("JSON 树引用无效");let a=i.left===null?void 0:r.nodes[i.left],s=i.right===null?void 0:r.nodes[i.right];(i.height!==1+Math.max(a?.height??0,s?.height??0)||Math.abs((a?.height??0)-(s?.height??0))>1||i.left!==null&&n[i.left].max>=i.key||i.right!==null&&n[i.right].min<=i.key)&&Rt("JSON 树顺序或平衡无效"),n.push({min:i.left===null?i.key:n[i.left].min,max:i.right===null?i.key:n[i.right].max})}),r.maps.some(i=>i!==null&&!Ec(i,r.nodes.length))&&Rt("JSON 映射根无效"),r}function eU(e,t){let r=(m,h=0,g=new Set)=>{if(h>64&&Rt("JSON 数据嵌套过深"),!(m===null||typeof m=="string"||typeof m=="boolean"||typeof m=="number"&&Number.isFinite(m))){if(typeof m!="object"||m===null||KQ.isProxy(m)||g.has(m))return Rt("JSON 数据无效");Object.getPrototypeOf(m)!==Object.prototype&&Object.getPrototypeOf(m)!==null&&!Array.isArray(m)&&Rt("JSON 数据必须为普通对象"),g.add(m);for(let v of Reflect.ownKeys(m)){if(Array.isArray(m)&&v==="length")continue;let w=Object.getOwnPropertyDescriptor(m,v);(typeof v!="string"||!w.enumerable||!("value"in w))&&Rt("JSON 数据不能包含访问器"),r(w.value,h+1,g)}Array.isArray(m)&&Object.keys(m).length!==m.length&&Rt("JSON 数组不能稀疏"),g.delete(m)}};r(e),r(t);let n=Vx(structuredClone(t)),i=structuredClone(e),o={validatedNodes:n.nodes.length,validationActions:0,validationResultMaps:0,validationEntries:0,validationMaterializedEntries:0,materializedMaps:0,materializedEntries:0,hashBytes:0,logicalHashBytes:0},a=new Set,s=new Set,c=new Set,l=new Map;for(let m of n.bindings){(!m||!Array.isArray(m.path)||m.path.length<1||m.path.length>16||m.path.some(w=>typeof w!="string"||["__proto__","constructor","prototype"].includes(w))||!Ec(m.map,n.maps.length)||Object.keys(m).some(w=>!["path","map"].includes(w)))&&Rt("JSON 池绑定无效");let h=JSON.stringify(m.path);(s.has(h)||m.path.some((w,y)=>a.has(JSON.stringify(m.path.slice(0,y+1)))))&&Rt("JSON 池绑定重复或重叠"),a.add(h),m.path.forEach((w,y)=>s.add(JSON.stringify(m.path.slice(0,y+1))));let g=i;for(let w of m.path.slice(0,-1))(!g||typeof g!="object"||!Object.hasOwn(g,w))&&Rt("JSON 池绑定缺失"),g=g[w];let v=m.path.at(-1);(!g||!Object.hasOwn(g,v)||!g[v]||typeof g[v]!="object"||Array.isArray(g[v])||Object.keys(g[v]).length)&&Rt("JSON 池绑定必须替换空对象"),Object.defineProperty(g,v,{value:ZQ({pool:n,root:n.maps[m.map],stats:o,checked:c,origins:l}),enumerable:!0,writable:!0,configurable:!0})}let u=new WeakMap,f=new Map,d=m=>{if(!m||typeof m!="object")return 0;let h=u.get(m);if(h!==void 0)return h;let g=oo.get(m),v=y=>{if(y===null)return 0;let R=f.get(y);if(R!==void 0)return R;let N=n.nodes[y],b=Math.max(1+d(n.values[N.value]),v(N.left),v(N.right));return f.set(y,b),b},w=g?v(g.root):Object.values(m).reduce((y,R)=>Math.max(y,1+d(R)),0);return u.set(m,w),w};d(i)>64&&Rt("JSON 逻辑数据嵌套超过 64 层"),Ku(n),Ku(i);let p=m=>{if(!(!m||typeof m!="object"||oo.has(m)||zu.has(m))){zu.set(m,o);for(let h of Object.values(m))p(h)}};return p(i),{value:i,stats:o,materialize:(m=[])=>Pr(m.reduce((h,g)=>h?.[g],i)),hash:()=>ei(i)}}function Ku(e){let t=new WeakSet,r=n=>{if(!(!n||typeof n!="object"||oo.has(n)||t.has(n))){t.add(n);for(let i of Object.values(n))r(i);Object.freeze(n)}};return r(e),e}function Pr(e){if(e===null||typeof e!="object")return e;let t=oo.get(e);if(t){t.stats.materializedMaps++;let r=[...xm(t)];return t.stats.materializedEntries+=r.length,Object.fromEntries(r.map(([n,i])=>[n,Pr(i)]))}return Array.isArray(e)?e.map(Pr):Object.fromEntries(Object.entries(e).map(([r,n])=>[r,Pr(n)]))}function Pm(e,t){let r=oo.get(e);if(!r){for(let[i,o]of Object.entries(e))t(i,o);return}r.stats.validationResultMaps++;let n=i=>{if(i===null||r.checked.has(i))return;let o=r.pool.nodes[i];n(o.left),t(o.key,r.pool.values[o.value]),r.stats.validationEntries++,n(o.right),r.checked.add(i)};n(r.root)}function Tm(e,t,r){let n=oo.get(e),i=(s,c)=>{let l=c.sequence;return t.get(l)!==s&&Rt("WorkflowRun 结果来源不一致"),l};if(!n){for(let[s,c]of Object.entries(e))i(s,c)>=r&&Rt("WorkflowRun 结果序号无效");return}let o=n.origins.get(t);o||(o=new Map,n.origins.set(t,o));let a=s=>{if(s===null)return 0;let c=o.get(s);if(c!==void 0)return c;let l=n.pool.nodes[s],u=Math.max(i(l.key,n.pool.values[l.value]),a(l.left),a(l.right));return o.set(s,u),u};a(n.root)>=r&&Rt("WorkflowRun 结果序号无效")}function tU(e){return Object.keys(e).sort((t,r)=>{let n=i=>String(Number(i))===i&&Number.isInteger(Number(i))&&Number(i)>=0&&Number(i)<4294967295;return n(t)||n(r)?n(t)&&n(r)?Number(t)-Number(r):n(t)?-1:1:t<r?-1:t>r?1:0})}function ei(e,t={}){let r=GQ("sha256"),n=e&&typeof e=="object"?zu.get(e):void 0,i=l=>{if(!l||typeof l!="object")return;let u=oo.get(l)?.stats??zu.get(l);if(u)return u;for(let f of Object.values(l)){let d=i(f);if(d)return d}};n??=i(e);let o=n&&t.cachePrefixes!==!1?Wx.get(n):void 0;n&&!o&&t.cachePrefixes!==!1&&(o={root:{hash:r.copy(),next:new Map},size:0},Wx.set(n,o));let a=o?.root,s=l=>{let u=Buffer.byteLength(l);n&&(n.logicalHashBytes+=u);let f=a?.next.get(l);if(f){r=f.hash.copy(),a=f;return}if(r.update(l),n&&(n.hashBytes+=u),a&&o&&o.size<1e5){let d={hash:r.copy(),next:new Map};a.next.set(l,d),a=d,o.size++}else a=void 0},c=l=>{if(l===null||typeof l!="object"){s(JSON.stringify(l));return}if(Array.isArray(l)){s("["),l.forEach((u,f)=>{f&&s(","),c(u)}),s("]");return}s("{"),tU(l).forEach((u,f)=>{f&&s(","),s(JSON.stringify(u)+":"),c(l[u])}),s("}")};return c(e),r.digest("hex")}function Gu(e){return zu.get(e)??oo.get(e)?.stats}function Om(e,t,r=!0){let n=eU(e,t);return r?n.materialize():n.value}var $x,Dx,oo,zu,Rt,Ec,Wx,Ga=x(()=>{"use strict";$x=new WeakMap,Dx=new WeakMap;oo=new WeakMap,zu=new WeakMap;Rt=e=>{throw new Error(e)},Ec=(e,t)=>Number.isSafeInteger(e)&&Number(e)>=0&&Number(e)<t;Wx=new WeakMap});function Dk(e){return typeof e=="string"&&e.trim().length>0&&e.length<=4096}function ae(e){throw new A("INVALID_RUN",e)}function Wt(e,t){return(!e||typeof e!="object"||Array.isArray(e))&&ae(`${t} 必须是 JSON 对象`),e}function Pn(e,t,r){for(let n of Object.keys(e))t.includes(n)||ae(`${r} 包含不支持的字段:${n}`)}function Xe(e,t){return(typeof e!="string"||!e.trim()||e.length>4096)&&ae(`${t} 必须是非空字符串且不超过 4096 字符`),e}function Cc(e,t,r=0){return(!Number.isSafeInteger(e)||e<r)&&ae(`${t} 必须是大于等于 ${r} 的安全整数`),e}function ea(e,t){return(typeof e!="string"||!/^[a-f0-9]{64}$/.test(e))&&ae(`${t} 必须是 SHA-256 摘要`),e}function Fx(e,t,r=!1){let n=Wt(e,t);Pn(n,r?["id","version","hash"]:["id","version"],t);let i={id:Xe(n.id,`${t}.id`),version:Xe(n.version,`${t}.version`)};return r&&(i.hash=ea(n.hash,`${t}.hash`)),i}function Yu(e,t,r){let n=Wt(e,t);if(!r&&In(n)&&Ux.has(n))return n;let i=(o,a)=>{Xe(o,`${t} step id`);let s=Wt(a,`${t}.${o}`);Pn(s,["sequence","value"],`${t}.${o}`),(!Object.hasOwn(s,"sequence")||!Object.hasOwn(s,"value"))&&ae(`${t}.${o} 缺少 sequence 或 value`),Cc(s.sequence,`${t}.${o}.sequence`,1)};if(r)r.visitResults(n,i);else for(let[o,a]of Object.entries(n))i(o,a);return n}function Hx(e,t,r){let n=Wt(e,t);return Pn(n,["from","to","results","activation"],t),(!Object.hasOwn(n,"from")||!Object.hasOwn(n,"to")||!Object.hasOwn(n,"results"))&&ae(`${t} 缺少 from、to 或 results`),{from:n.from===null?null:Xe(n.from,`${t}.from`),to:Xe(n.to,`${t}.to`),results:Yu(n.results,`${t}.results`,r),...Object.hasOwn(n,"activation")?{activation:n.activation}:{}}}function jm(e,t,r,n){let i=`${t}:`;e.startsWith(i)||ae(`${r} 不属于当前 Run`);let o=e.slice(i.length);/^[1-9][0-9]*$/.test(o)||ae(`${r} 的步骤序号无效`);let a=Number(o);return(!Number.isSafeInteger(a)||a>n)&&ae(`${r} 的步骤序号超出 Run 范围`),a}function rU(e,t,r,n){let i=Wt(e,"Wait");Pn(i,["id","stepId","sequence","status","proposal","proposalHash","choices","results","decision"],"Wait");for(let f of["id","stepId","sequence","status","proposal","proposalHash","choices","results"])Object.hasOwn(i,f)||ae(`Wait 缺少 ${f}`);let o=Xe(i.id,"Wait.id"),a=Xe(i.stepId,"Wait.stepId"),s=Cc(i.sequence,"Wait.sequence",1);(s>r||jm(o,t,"Wait.id",r)!==s)&&ae("Wait 的 id 与 sequence 不一致"),["pending","resolved","cancelled"].includes(String(i.status))||ae("Wait.status 无效"),(!Array.isArray(i.choices)||i.choices.length===0)&&ae("Wait.choices 必须是非空数组");let c=i.choices.map(f=>Xe(f,"Wait.choices"));new Set(c).size!==c.length&&ae("Wait.choices 不能重复");let l=ea(i.proposalHash,"Wait.proposalHash");D(i.proposal)!==l&&ae("Wait.proposal 与 proposalHash 不一致");let u={id:o,stepId:a,sequence:s,status:i.status,proposal:i.proposal,proposalHash:l,choices:c,results:Yu(i.results,"Wait.results",n)};if(i.decision!==void 0){let f=Wt(i.decision,"Wait.decision");Pn(f,["id","choice","proposalHash","reason"],"Wait.decision"),f.reason!==void 0&&!Dk(f.reason)&&ae("Wait.decision.reason 必须是 1 到 4096 字符的非空文本");let d={id:Xe(f.id,"Wait.decision.id"),choice:Xe(f.choice,"Wait.decision.choice"),proposalHash:ea(f.proposalHash,"Wait.decision.proposalHash"),...f.reason===void 0?{}:{reason:f.reason}};(i.status!=="resolved"||!c.includes(d.choice)||d.proposalHash!==l)&&ae("Wait.decision 与 Wait 状态、选择或提案不一致"),u.decision=d}else i.status==="resolved"&&ae("已解决的 Wait 必须保存对应 decision");return u}function nU(e,t,r,n){let i=Wt(e,"EvidenceWait");Pn(i,["id","stepId","sequence","kind","status","results","receipt","invalidation"],"EvidenceWait");let o=Xe(i.id,"EvidenceWait.id"),a=Cc(i.sequence,"EvidenceWait.sequence",1);(a>r||jm(o,t,"EvidenceWait.id",r)!==a)&&ae("EvidenceWait 的 id 与 sequence 不一致"),["pending","resolved","invalidated","cancelled"].includes(String(i.status))||ae("EvidenceWait.status 无效");let s={id:o,stepId:Xe(i.stepId,"EvidenceWait.stepId"),sequence:a,kind:Xe(i.kind,"EvidenceWait.kind"),status:i.status,results:Yu(i.results,"EvidenceWait.results",n)};if(i.receipt!==void 0){let c=Wt(i.receipt,"EvidenceWait.receipt");Pn(c,["ref","contentHash","submissionId"],"EvidenceWait.receipt"),s.receipt={ref:Xe(c.ref,"EvidenceWait.receipt.ref"),contentHash:ea(c.contentHash,"EvidenceWait.receipt.contentHash"),submissionId:Xe(c.submissionId,"EvidenceWait.receipt.submissionId")}}if(i.invalidation!==void 0){let c=Wt(i.invalidation,"EvidenceWait.invalidation");Pn(c,["ref","contentHash","submissionId","reason"],"EvidenceWait.invalidation"),s.invalidation={ref:Xe(c.ref,"EvidenceWait.invalidation.ref"),contentHash:ea(c.contentHash,"EvidenceWait.invalidation.contentHash"),submissionId:Xe(c.submissionId,"EvidenceWait.invalidation.submissionId"),reason:Xe(c.reason,"EvidenceWait.invalidation.reason")}}return(s.status==="resolved"!=!!s.receipt||s.status==="invalidated"!=!!s.invalidation)&&ae("EvidenceWait.receipt 与状态不一致"),s}function Tn(e,t){let r=Wt(pt(e),"WorkflowRun");return Bm(r,t)}function Jx(e,t){if(e&&typeof e=="object"&&Bk.has(e)&&In(e)){let r=e;return t!==void 0&&r.runId!==t&&ae("WorkflowRun.runId 与存储键不一致"),r}return xn(e),zx(Bm(Wt(structuredClone(e),"WorkflowRun"),t))}function $m(e,t,r){return Bm(Wt(e,"WorkflowRun"),t,void 0,r)}function Dm(e,t){return xn(e),Bm(Wt(e,"WorkflowRun"),e.runId,t&&Bk.has(t)&&In(t)?t:void 0),zx(e)}function zx(e){za(e),Bk.add(e);for(let r of e.actions)Qx.add(r);let t=r=>Ux.add(r);for(let r of Object.values(e.actionContexts))t(r.results);for(let r of e.waits)t(r.results);for(let r of e.evidenceWaits??[])t(r.results);for(let r of e.ready)t(r.results);for(let r of Object.values(e.joins))for(let n of Object.values(r))for(let i of n)t(i.results);return t(e.outputs),e}function Bm(e,t,r,n){Pn(e,Mx,"WorkflowRun");for(let q of Mx.filter(ne=>ne!=="reason"&&ne!=="state"&&ne!=="evidenceWaits"&&ne!=="initialStateHash"&&ne!=="commands"))Object.hasOwn(e,q)||ae(`WorkflowRun 缺少 ${q}`);if(e.protocolVersion!==1||e.schemaVersion!==1)throw new A("UNSUPPORTED_PROTOCOL","当前 Runtime 不支持此 Run 协议或状态版本");let i=Xe(e.runId,"WorkflowRun.runId");t!==void 0&&i!==t&&ae("WorkflowRun.runId 与存储键不一致");let o=Cc(e.revision,"WorkflowRun.revision",1),a=Cc(e.sequence,"WorkflowRun.sequence"),s=Fx(e.workflow,"WorkflowRun.workflow",!0);["running","waiting","completed","failed","cancelled"].includes(String(e.status))||ae("WorkflowRun.status 无效"),e.reason!==void 0&&Xe(e.reason,"WorkflowRun.reason"),Object.hasOwn(e,"input")||ae("WorkflowRun 缺少 input");let c=Wt(e.definitionHashes,"WorkflowRun.definitionHashes");Object.keys(c).length===0&&ae("WorkflowRun.definitionHashes 不能为空");for(let[q,ne]of Object.entries(c)){let he;try{he=JSON.parse(q)}catch{ae("WorkflowRun.definitionHashes 包含无效的工作流引用")}(!Array.isArray(he)||he.length!==2||typeof he[0]!="string"||typeof he[1]!="string"||JSON.stringify(he)!==q)&&ae("WorkflowRun.definitionHashes 包含非规范的工作流引用"),ea(ne,`WorkflowRun.definitionHashes.${q}`)}let l=JSON.stringify([s.id,s.version]);c[l]!==s.hash&&ae("WorkflowRun.workflow 与固定定义摘要不一致"),(!Array.isArray(e.lineage)||e.lineage.length>32)&&ae("WorkflowRun.lineage 必须是最多 32 层的数组");let u=e.lineage.map(q=>Xe(q,"WorkflowRun.lineage"));(new Set(u).size!==u.length||u.includes(i))&&ae("WorkflowRun.lineage 不能重复或包含当前 Run"),(!Array.isArray(e.actions)||!Array.isArray(e.waits))&&ae("WorkflowRun.actions 和 waits 必须是数组");let f=e.actions.map(q=>{let ne;try{ne=q&&typeof q=="object"&&Qx.has(q)&&In(q)?q:$k(q,n?.hash(q.input))}catch(he){if(he instanceof A&&he.code==="UNSUPPORTED_PROTOCOL")throw he;ae(`WorkflowRun.actions 包含无效 Action:${he.message}`)}return ne.executionOrigin&&ne.executionOrigin.workflow.id!==s.id&&ae("Action 执行来源不属于当前工作流"),ne.runId!==i&&ae(`Action ${ne.id} 不属于当前 Run`),new Set(ne.requiredCapabilities).size!==ne.requiredCapabilities.length&&ae(`Action ${ne.id} 的 requiredCapabilities 不能重复`),ne}),d=new Map(f.map(q=>[q.id,q]));e.commands!==void 0&&!Array.isArray(e.commands)&&ae("WorkflowRun.commands 必须是数组");let p=e.commands?.map(q=>{let ne=Wt(q,"WorkflowRun.commands item");Pn(ne,["id","name","inputHash","actionId"],"WorkflowRun.commands item");let he={id:Xe(ne.id,"WorkflowRun.commands.id"),name:Xe(ne.name,"WorkflowRun.commands.name"),inputHash:ea(ne.inputHash,"WorkflowRun.commands.inputHash"),actionId:Xe(ne.actionId,"WorkflowRun.commands.actionId")};return d.has(he.actionId)||ae("WorkflowRun.commands 指向不存在的 Action"),he});p&&new Set(p.map(q=>q.id)).size!==p.length&&ae("WorkflowRun.commands 标识不能重复");let m=e.waits.map(q=>rU(q,i,a,n));e.evidenceWaits!==void 0&&!Array.isArray(e.evidenceWaits)&&ae("WorkflowRun.evidenceWaits 必须是数组");let h=e.evidenceWaits?.map(q=>nU(q,i,a,n))??[],g=new Map;for(let q of f){let ne=jm(q.id,i,"Action.id",a);g.has(ne)&&ae("WorkflowRun 的步骤序号不能重复"),g.set(ne,q.stepId)}for(let q of m)g.has(q.sequence)&&ae("WorkflowRun 的步骤序号不能重复"),g.set(q.sequence,q.stepId);for(let q of h)g.has(q.sequence)&&ae("WorkflowRun 的步骤序号不能重复"),g.set(q.sequence,q.stepId);g.size!==a&&ae("WorkflowRun.sequence 与已激活步骤数量不一致");let v=Wt(e.actionContexts,"WorkflowRun.actionContexts");Object.keys(v).length!==f.length&&ae("WorkflowRun.actionContexts 必须与 actions 一一对应");let w=new Map,y=r?new Map([...r.actions.map(q=>[r.actionContexts[q.id].sequence,q.stepId]),...r.waits.map(q=>[q.sequence,q.stepId]),...(r.evidenceWaits??[]).map(q=>[q.sequence,q.stepId])]):void 0;if(r&&y&&r.runId===i&&[...y].every(([q,ne])=>g.get(q)===ne)){let q=(ne,he)=>w.set(ne,Math.min(w.get(ne)??1/0,he));for(let ne of Object.values(r.actionContexts))q(ne.results,ne.sequence);for(let ne of r.waits)q(ne.results,ne.sequence);for(let ne of r.evidenceWaits??[])q(ne.results,ne.sequence);for(let ne of r.ready)q(ne.results,r.sequence+1);for(let ne of Object.values(r.joins))for(let he of Object.values(ne))for(let Ot of he)q(Ot.results,r.sequence+1);q(r.outputs,r.sequence+1)}let R=new Map;function N(q,ne){let he=ne??a+1;if(n){n.validateOrigins(q,g,he);return}let Ot=w.get(q);if(!(Ot!==void 0&&he>=Ot&&In(q))&&!((R.get(q)??1/0)<=he)){R.set(q,he);for(let[_,S]of Object.entries(q))(S.sequence>=(ne??a+1)||g.get(S.sequence)!==_)&&ae(`WorkflowRun 结果 ${_} 的序号或来源不一致`)}}for(let q of f){Object.hasOwn(v,q.id)||ae(`Action ${q.id} 缺少上下文`);let ne=Wt(v[q.id],`actionContexts.${q.id}`);Pn(ne,["sequence","results"],`actionContexts.${q.id}`);let he=Cc(ne.sequence,`actionContexts.${q.id}.sequence`,1);he!==jm(q.id,i,"Action.id",a)&&ae(`Action ${q.id} 的上下文序号不一致`);let Ot=Yu(ne.results,`actionContexts.${q.id}.results`,n);N(Ot,he)}for(let q of m)N(q.results,q.sequence);for(let q of h)N(q.results,q.sequence);Array.isArray(e.ready)||ae("WorkflowRun.ready 必须是数组");let b=e.ready.map(q=>Hx(q,"WorkflowRun.ready token",n));for(let q of b)N(q.results);let E=Wt(e.joins,"WorkflowRun.joins"),I=Object.fromEntries(Object.entries(E).map(([q,ne])=>{Xe(q,"WorkflowRun.joins step id");let he=Wt(ne,`WorkflowRun.joins.${q}`),Ot=Object.fromEntries(Object.entries(he).map(([_,S])=>{Xe(_,"WorkflowRun.joins parent id"),Array.isArray(S)||ae(`WorkflowRun.joins.${q}.${_} 必须是数组`);let P=S.map(B=>{let V=Hx(B,`WorkflowRun.joins.${q}.${_}`,n);return(V.to!==q||V.from!==_)&&ae(`WorkflowRun.joins.${q}.${_} 包含错误来源的 token`),N(V.results),V});return[_,P]}));return[q,Ot]})),W=Yu(e.outputs,"WorkflowRun.outputs",n);N(W),Array.isArray(e.children)||ae("WorkflowRun.children 必须是数组");let F=e.children.map(q=>{let ne=Wt(q,"WorkflowRun.children item");Pn(ne,["actionId","runId","workflow"],"WorkflowRun.children item");let he=Fx(ne.workflow,"WorkflowRun.children.workflow"),Ot=Xe(ne.actionId,"WorkflowRun.children.actionId"),_=Xe(ne.runId,"WorkflowRun.children.runId"),S=d.get(Ot);return(!S||S.type!=="child_workflow"||S.ref!==`${he.id}@${he.version}`||_!==`child-${D(Ot)}`||!Object.hasOwn(c,JSON.stringify([he.id,he.version])))&&ae("WorkflowRun.children 与子工作流 Action 或固定定义不一致"),{actionId:Ot,runId:_,workflow:he}});(new Set(F.map(q=>q.actionId)).size!==F.length||f.filter(q=>q.type==="child_workflow").length!==F.length)&&ae("每个子工作流 Action 必须恰好对应一个 Child Run");let Z=f.some(q=>["pending","running","unknown"].includes(q.status)),Ae=m.some(q=>q.status==="pending"),re=h.some(q=>q.status==="pending"),nt=Object.values(I).some(q=>Object.values(q).some(ne=>ne.length>0));return e.status==="running"&&!Z&&b.length===0&&ae("running Run 必须包含待调度步骤、待执行或已派发的 Action"),e.status==="waiting"&&(Z||!Ae&&!re&&!nt||b.length>0)&&ae("waiting Run 必须只有未解决的 Wait 或不完整 join"),e.status==="completed"&&(Z||Ae||re||nt||b.length>0)&&ae("completed Run 不能遗留待执行、等待或 join 工作"),(e.status==="failed"||e.status==="cancelled")&&e.reason===void 0&&ae(`${String(e.status)} Run 必须记录停止原因`),{protocolVersion:1,schemaVersion:1,runId:i,revision:o,workflow:s,definitionHashes:c,...e.initialStateHash===void 0?{}:{initialStateHash:ea(e.initialStateHash,"WorkflowRun.initialStateHash")},input:e.input,...e.state===void 0?{}:{state:e.state},status:e.status,sequence:a,actions:f,...p===void 0?{}:{commands:p},actionContexts:v,waits:m,...e.evidenceWaits===void 0?{}:{evidenceWaits:h},ready:b,joins:I,outputs:W,children:F,lineage:u,...e.reason===void 0?{}:{reason:e.reason}}}var Qx,Ux,Bk,Mx,Xu=x(()=>{"use strict";Ka();_n();xr();Qx=new WeakSet,Ux=new WeakSet,Bk=new WeakSet,Mx=["protocolVersion","schemaVersion","runId","revision","workflow","definitionHashes","initialStateHash","input","state","status","sequence","actions","commands","actionContexts","waits","evidenceWaits","ready","joins","outputs","children","lineage","reason"]});import{randomUUID as iU}from"node:crypto";async function Ya(e,t){let r=await(e.readProjection?e.readProjection(t):e.read(t));if(!r)throw new A("RUN_NOT_FOUND",`找不到工作流实例:${t}`);Gu(r)||(xn(r),r=structuredClone(r),Ku(r));let n="run"in r?r.run:r;if(!n||n.runId!==r.runId||n.revision!==r.revision)throw new A("INVALID_RUN","Run 与存储 envelope 身份不一致");let i;try{i=$m(n,t,{hash:ei,visitResults:Pm,validateOrigins:Tm})}catch(s){throw s instanceof A?s:new A("INVALID_RUN",s instanceof Error?s.message:String(s))}Ku(i);let o=Gu(r);o&&(o.validationActions=i.actions.length,o.validationMaterializedEntries=o.materializedEntries);let a=e.queryScope??Kx.get(e);return a||(a=iU(),Kx.set(e,a)),Object.freeze({record:r,run:i,scope:a,stats:o,materialize:(s=[])=>Pr(s.reduce((c,l)=>c?.[l],i)),hash:()=>ei(i)})}function Wk(e,t){let{run:r,scope:n}=e;["current","summary","history","action","artifact"].includes(t.view)||ta("query.view 无效");let i={runId:r.runId,revision:r.revision,status:r.status,workflow:r.workflow,sequence:r.sequence},o={actions:r.actions.length,waits:r.waits.length,evidenceWaits:r.evidenceWaits?.length??0},a=r.actions.filter(d=>["pending","running","unknown"].includes(d.status)||d.status==="cancelled"&&d.claim&&!d.executionStop&&!d.cancellation);if(t.view==="summary")return Pr({...i,history:o,pending:{actions:a.length,waits:r.waits.filter(d=>d.status==="pending").length,evidenceWaits:(r.evidenceWaits??[]).filter(d=>d.status==="pending").length}});if(t.view==="current")return Pr({...i,input:r.input,...r.state===void 0?{}:{state:r.state},...r.reason===void 0?{}:{reason:r.reason},actions:a,waits:r.waits.filter(d=>d.status==="pending"),evidenceWaits:(r.evidenceWaits??[]).filter(d=>d.status==="pending"),outputs:r.outputs,history:o});if(t.view==="action"||t.view==="artifact"){let d=r.actions.find(h=>h.id===t.actionId);if(d||ta("query.actionId 不属于当前 Run"),t.view==="action")return Pr({...i,action:d,context:r.actionContexts[d.id]});let p=(d.outcome?.artifacts??[]).map(h=>({...h,artifactId:D({actionId:d.id,...h})})),m=t.artifactId===void 0?p:p.filter(h=>h.artifactId===t.artifactId);return t.artifactId!==void 0&&!m.length&&ta("query.artifactId 不属于所选 Action"),Pr({...i,actionId:d.id,artifacts:m})}let s=t.limit??25;(!Number.isSafeInteger(s)||s<1||s>100)&&ta("query.limit 必须在 1–100 之间");let c=t.filter??"all";["all","actions","waits","evidenceWaits"].includes(c)||ta("query.filter 无效");let l=D({scope:n,runId:r.runId,revision:r.revision,filter:c}),u=0;if(t.cursor)try{let d=JSON.parse(Buffer.from(t.cursor,"base64url").toString("utf8"));(d.binding!==l||!Number.isSafeInteger(d.offset)||d.offset<0||Object.keys(d).some(p=>!["binding","offset"].includes(p)))&&ta("query.cursor 与当前存储、版本或筛选不匹配"),u=d.offset}catch{ta("query.cursor 无效或已经过期")}let f=[...c==="all"||c==="actions"?r.actions.map((d,p)=>({kind:"action",sequence:r.actionContexts[d.id].sequence,path:["actions",String(p)]})):[],...c==="all"||c==="waits"?r.waits.map((d,p)=>({kind:"wait",sequence:d.sequence,path:["waits",String(p)]})):[],...c==="all"||c==="evidenceWaits"?(r.evidenceWaits??[]).map((d,p)=>({kind:"evidenceWait",sequence:d.sequence,path:["evidenceWaits",String(p)]})):[]].sort((d,p)=>p.sequence-d.sequence);return u>f.length&&ta("query.cursor 超出历史范围"),{...Pr(i),records:f.slice(u,u+s).map(d=>({kind:d.kind,sequence:d.sequence,value:e.materialize(d.path)})),total:f.length,...u+s<f.length?{nextCursor:Buffer.from(JSON.stringify({binding:l,offset:u+s})).toString("base64url")}:{}}}var Kx,ta,qk=x(()=>{"use strict";Ga();_n();Xu();xr();Kx=new WeakMap;ta=e=>{throw new A("INVALID_REQUEST",e)}});var td=$(Me=>{"use strict";Object.defineProperty(Me,"__esModule",{value:!0});Me.regexpCode=Me.getEsmExportName=Me.getProperty=Me.safeStringify=Me.stringify=Me.strConcat=Me.addCodeArg=Me.str=Me._=Me.nil=Me._Code=Me.Name=Me.IDENTIFIER=Me._CodeOrName=void 0;var Zu=class{};Me._CodeOrName=Zu;Me.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;var Xa=class extends Zu{constructor(t){if(super(),!Me.IDENTIFIER.test(t))throw new Error("CodeGen: name must be a valid identifier");this.str=t}toString(){return this.str}emptyStr(){return!1}get names(){return{[this.str]:1}}};Me.Name=Xa;var On=class extends Zu{constructor(t){super(),this._items=typeof t=="string"?[t]:t}toString(){return this.str}emptyStr(){if(this._items.length>1)return!1;let t=this._items[0];return t===""||t==='""'}get str(){var t;return(t=this._str)!==null&&t!==void 0?t:this._str=this._items.reduce((r,n)=>`${r}${n}`,"")}get names(){var t;return(t=this._names)!==null&&t!==void 0?t:this._names=this._items.reduce((r,n)=>(n instanceof Xa&&(r[n.str]=(r[n.str]||0)+1),r),{})}};Me._Code=On;Me.nil=new On("");function Gx(e,...t){let r=[e[0]],n=0;for(;n<t.length;)Vk(r,t[n]),r.push(e[++n]);return new On(r)}Me._=Gx;var Lk=new On("+");function Yx(e,...t){let r=[ed(e[0])],n=0;for(;n<t.length;)r.push(Lk),Vk(r,t[n]),r.push(Lk,ed(e[++n]));return oU(r),new On(r)}Me.str=Yx;function Vk(e,t){t instanceof On?e.push(...t._items):t instanceof Xa?e.push(t):e.push(cU(t))}Me.addCodeArg=Vk;function oU(e){let t=1;for(;t<e.length-1;){if(e[t]===Lk){let r=aU(e[t-1],e[t+1]);if(r!==void 0){e.splice(t-1,3,r);continue}e[t++]="+"}t++}}function aU(e,t){if(t==='""')return e;if(e==='""')return t;if(typeof e=="string")return t instanceof Xa||e[e.length-1]!=='"'?void 0:typeof t!="string"?`${e.slice(0,-1)}${t}"`:t[0]==='"'?e.slice(0,-1)+t.slice(1):void 0;if(typeof t=="string"&&t[0]==='"'&&!(e instanceof Xa))return`"${e}${t.slice(1)}`}function sU(e,t){return t.emptyStr()?e:e.emptyStr()?t:Yx`${e}${t}`}Me.strConcat=sU;function cU(e){return typeof e=="number"||typeof e=="boolean"||e===null?e:ed(Array.isArray(e)?e.join(","):e)}function lU(e){return new On(ed(e))}Me.stringify=lU;function ed(e){return JSON.stringify(e).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}Me.safeStringify=ed;function uU(e){return typeof e=="string"&&Me.IDENTIFIER.test(e)?new On(`.${e}`):Gx`[${e}]`}Me.getProperty=uU;function dU(e){if(typeof e=="string"&&Me.IDENTIFIER.test(e))return new On(`${e}`);throw new Error(`CodeGen: invalid export name: ${e}, use explicit $id name mapping`)}Me.getEsmExportName=dU;function fU(e){return new On(e.toString())}Me.regexpCode=fU});var Hk=$(Yr=>{"use strict";Object.defineProperty(Yr,"__esModule",{value:!0});Yr.ValueScope=Yr.ValueScopeName=Yr.Scope=Yr.varKinds=Yr.UsedValueState=void 0;var Gr=td(),Mk=class extends Error{constructor(t){super(`CodeGen: "code" for ${t} not defined`),this.value=t.value}},Wm;(function(e){e[e.Started=0]="Started",e[e.Completed=1]="Completed"})(Wm||(Yr.UsedValueState=Wm={}));Yr.varKinds={const:new Gr.Name("const"),let:new Gr.Name("let"),var:new Gr.Name("var")};var qm=class{constructor({prefixes:t,parent:r}={}){this._names={},this._prefixes=t,this._parent=r}toName(t){return t instanceof Gr.Name?t:this.name(t)}name(t){return new Gr.Name(this._newName(t))}_newName(t){let r=this._names[t]||this._nameGroup(t);return`${t}${r.index++}`}_nameGroup(t){var r,n;if(!((n=(r=this._parent)===null||r===void 0?void 0:r._prefixes)===null||n===void 0)&&n.has(t)||this._prefixes&&!this._prefixes.has(t))throw new Error(`CodeGen: prefix "${t}" is not allowed in this scope`);return this._names[t]={prefix:t,index:0}}};Yr.Scope=qm;var Lm=class extends Gr.Name{constructor(t,r){super(r),this.prefix=t}setValue(t,{property:r,itemIndex:n}){this.value=t,this.scopePath=(0,Gr._)`.${new Gr.Name(r)}[${n}]`}};Yr.ValueScopeName=Lm;var pU=(0,Gr._)`\n`,Fk=class extends qm{constructor(t){super(t),this._values={},this._scope=t.scope,this.opts={...t,_n:t.lines?pU:Gr.nil}}get(){return this._scope}name(t){return new Lm(t,this._newName(t))}value(t,r){var n;if(r.ref===void 0)throw new Error("CodeGen: ref must be passed in value");let i=this.toName(t),{prefix:o}=i,a=(n=r.key)!==null&&n!==void 0?n:r.ref,s=this._values[o];if(s){let u=s.get(a);if(u)return u}else s=this._values[o]=new Map;s.set(a,i);let c=this._scope[o]||(this._scope[o]=[]),l=c.length;return c[l]=r.ref,i.setValue(r,{property:o,itemIndex:l}),i}getValue(t,r){let n=this._values[t];if(n)return n.get(r)}scopeRefs(t,r=this._values){return this._reduceValues(r,n=>{if(n.scopePath===void 0)throw new Error(`CodeGen: name "${n}" has no value`);return(0,Gr._)`${t}${n.scopePath}`})}scopeCode(t=this._values,r,n){return this._reduceValues(t,i=>{if(i.value===void 0)throw new Error(`CodeGen: name "${i}" has no value`);return i.value.code},r,n)}_reduceValues(t,r,n={},i){let o=Gr.nil;for(let a in t){let s=t[a];if(!s)continue;let c=n[a]=n[a]||new Map;s.forEach(l=>{if(c.has(l))return;c.set(l,Wm.Started);let u=r(l);if(u){let f=this.opts.es5?Yr.varKinds.var:Yr.varKinds.const;o=(0,Gr._)`${o}${f} ${l} = ${u};${this.opts._n}`}else if(u=i?.(l))o=(0,Gr._)`${o}${u}${this.opts._n}`;else throw new Mk(l);c.set(l,Wm.Completed)})}return o}};Yr.ValueScope=Fk});var Ce=$(Ne=>{"use strict";Object.defineProperty(Ne,"__esModule",{value:!0});Ne.or=Ne.and=Ne.not=Ne.CodeGen=Ne.operators=Ne.varKinds=Ne.ValueScopeName=Ne.ValueScope=Ne.Scope=Ne.Name=Ne.regexpCode=Ne.stringify=Ne.getProperty=Ne.nil=Ne.strConcat=Ne.str=Ne._=void 0;var Oe=td(),ti=Hk(),ra=td();Object.defineProperty(Ne,"_",{enumerable:!0,get:function(){return ra._}});Object.defineProperty(Ne,"str",{enumerable:!0,get:function(){return ra.str}});Object.defineProperty(Ne,"strConcat",{enumerable:!0,get:function(){return ra.strConcat}});Object.defineProperty(Ne,"nil",{enumerable:!0,get:function(){return ra.nil}});Object.defineProperty(Ne,"getProperty",{enumerable:!0,get:function(){return ra.getProperty}});Object.defineProperty(Ne,"stringify",{enumerable:!0,get:function(){return ra.stringify}});Object.defineProperty(Ne,"regexpCode",{enumerable:!0,get:function(){return ra.regexpCode}});Object.defineProperty(Ne,"Name",{enumerable:!0,get:function(){return ra.Name}});var Hm=Hk();Object.defineProperty(Ne,"Scope",{enumerable:!0,get:function(){return Hm.Scope}});Object.defineProperty(Ne,"ValueScope",{enumerable:!0,get:function(){return Hm.ValueScope}});Object.defineProperty(Ne,"ValueScopeName",{enumerable:!0,get:function(){return Hm.ValueScopeName}});Object.defineProperty(Ne,"varKinds",{enumerable:!0,get:function(){return Hm.varKinds}});Ne.operators={GT:new Oe._Code(">"),GTE:new Oe._Code(">="),LT:new Oe._Code("<"),LTE:new Oe._Code("<="),EQ:new Oe._Code("==="),NEQ:new Oe._Code("!=="),NOT:new Oe._Code("!"),OR:new Oe._Code("||"),AND:new Oe._Code("&&"),ADD:new Oe._Code("+")};var ao=class{optimizeNodes(){return this}optimizeNames(t,r){return this}},Qk=class extends ao{constructor(t,r,n){super(),this.varKind=t,this.name=r,this.rhs=n}render({es5:t,_n:r}){let n=t?ti.varKinds.var:this.varKind,i=this.rhs===void 0?"":` = ${this.rhs}`;return`${n} ${this.name}${i};`+r}optimizeNames(t,r){if(t[this.name.str])return this.rhs&&(this.rhs=Ic(this.rhs,t,r)),this}get names(){return this.rhs instanceof Oe._CodeOrName?this.rhs.names:{}}},Vm=class extends ao{constructor(t,r,n){super(),this.lhs=t,this.rhs=r,this.sideEffects=n}render({_n:t}){return`${this.lhs} = ${this.rhs};`+t}optimizeNames(t,r){if(!(this.lhs instanceof Oe.Name&&!t[this.lhs.str]&&!this.sideEffects))return this.rhs=Ic(this.rhs,t,r),this}get names(){let t=this.lhs instanceof Oe.Name?{}:{...this.lhs.names};return Fm(t,this.rhs)}},Uk=class extends Vm{constructor(t,r,n,i){super(t,n,i),this.op=r}render({_n:t}){return`${this.lhs} ${this.op}= ${this.rhs};`+t}},Jk=class extends ao{constructor(t){super(),this.label=t,this.names={}}render({_n:t}){return`${this.label}:`+t}},zk=class extends ao{constructor(t){super(),this.label=t,this.names={}}render({_n:t}){return`break${this.label?` ${this.label}`:""};`+t}},Kk=class extends ao{constructor(t){super(),this.error=t}render({_n:t}){return`throw ${this.error};`+t}get names(){return this.error.names}},Gk=class extends ao{constructor(t){super(),this.code=t}render({_n:t}){return`${this.code};`+t}optimizeNodes(){return`${this.code}`?this:void 0}optimizeNames(t,r){return this.code=Ic(this.code,t,r),this}get names(){return this.code instanceof Oe._CodeOrName?this.code.names:{}}},rd=class extends ao{constructor(t=[]){super(),this.nodes=t}render(t){return this.nodes.reduce((r,n)=>r+n.render(t),"")}optimizeNodes(){let{nodes:t}=this,r=t.length;for(;r--;){let n=t[r].optimizeNodes();Array.isArray(n)?t.splice(r,1,...n):n?t[r]=n:t.splice(r,1)}return t.length>0?this:void 0}optimizeNames(t,r){let{nodes:n}=this,i=n.length;for(;i--;){let o=n[i];o.optimizeNames(t,r)||(mU(t,o.names),n.splice(i,1))}return n.length>0?this:void 0}get names(){return this.nodes.reduce((t,r)=>ts(t,r.names),{})}},so=class extends rd{render(t){return"{"+t._n+super.render(t)+"}"+t._n}},Yk=class extends rd{},_c=class extends so{};_c.kind="else";var Za=class e extends so{constructor(t,r){super(r),this.condition=t}render(t){let r=`if(${this.condition})`+super.render(t);return this.else&&(r+="else "+this.else.render(t)),r}optimizeNodes(){super.optimizeNodes();let t=this.condition;if(t===!0)return this.nodes;let r=this.else;if(r){let n=r.optimizeNodes();r=this.else=Array.isArray(n)?new _c(n):n}if(r)return t===!1?r instanceof e?r:r.nodes:this.nodes.length?this:new e(Xx(t),r instanceof e?[r]:r.nodes);if(!(t===!1||!this.nodes.length))return this}optimizeNames(t,r){var n;if(this.else=(n=this.else)===null||n===void 0?void 0:n.optimizeNames(t,r),!!(super.optimizeNames(t,r)||this.else))return this.condition=Ic(this.condition,t,r),this}get names(){let t=super.names;return Fm(t,this.condition),this.else&&ts(t,this.else.names),t}};Za.kind="if";var es=class extends so{};es.kind="for";var Xk=class extends es{constructor(t){super(),this.iteration=t}render(t){return`for(${this.iteration})`+super.render(t)}optimizeNames(t,r){if(super.optimizeNames(t,r))return this.iteration=Ic(this.iteration,t,r),this}get names(){return ts(super.names,this.iteration.names)}},Zk=class extends es{constructor(t,r,n,i){super(),this.varKind=t,this.name=r,this.from=n,this.to=i}render(t){let r=t.es5?ti.varKinds.var:this.varKind,{name:n,from:i,to:o}=this;return`for(${r} ${n}=${i}; ${n}<${o}; ${n}++)`+super.render(t)}get names(){let t=Fm(super.names,this.from);return Fm(t,this.to)}},Mm=class extends es{constructor(t,r,n,i){super(),this.loop=t,this.varKind=r,this.name=n,this.iterable=i}render(t){return`for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})`+super.render(t)}optimizeNames(t,r){if(super.optimizeNames(t,r))return this.iterable=Ic(this.iterable,t,r),this}get names(){return ts(super.names,this.iterable.names)}},nd=class extends so{constructor(t,r,n){super(),this.name=t,this.args=r,this.async=n}render(t){return`${this.async?"async ":""}function ${this.name}(${this.args})`+super.render(t)}};nd.kind="func";var id=class extends rd{render(t){return"return "+super.render(t)}};id.kind="return";var eb=class extends so{render(t){let r="try"+super.render(t);return this.catch&&(r+=this.catch.render(t)),this.finally&&(r+=this.finally.render(t)),r}optimizeNodes(){var t,r;return super.optimizeNodes(),(t=this.catch)===null||t===void 0||t.optimizeNodes(),(r=this.finally)===null||r===void 0||r.optimizeNodes(),this}optimizeNames(t,r){var n,i;return super.optimizeNames(t,r),(n=this.catch)===null||n===void 0||n.optimizeNames(t,r),(i=this.finally)===null||i===void 0||i.optimizeNames(t,r),this}get names(){let t=super.names;return this.catch&&ts(t,this.catch.names),this.finally&&ts(t,this.finally.names),t}},od=class extends so{constructor(t){super(),this.error=t}render(t){return`catch(${this.error})`+super.render(t)}};od.kind="catch";var ad=class extends so{render(t){return"finally"+super.render(t)}};ad.kind="finally";var tb=class{constructor(t,r={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...r,_n:r.lines?`
|
|
188
|
+
`:""},this._extScope=t,this._scope=new ti.Scope({parent:t}),this._nodes=[new Yk]}toString(){return this._root.render(this.opts)}name(t){return this._scope.name(t)}scopeName(t){return this._extScope.name(t)}scopeValue(t,r){let n=this._extScope.value(t,r);return(this._values[n.prefix]||(this._values[n.prefix]=new Set)).add(n),n}getScopeValue(t,r){return this._extScope.getValue(t,r)}scopeRefs(t){return this._extScope.scopeRefs(t,this._values)}scopeCode(){return this._extScope.scopeCode(this._values)}_def(t,r,n,i){let o=this._scope.toName(r);return n!==void 0&&i&&(this._constants[o.str]=n),this._leafNode(new Qk(t,o,n)),o}const(t,r,n){return this._def(ti.varKinds.const,t,r,n)}let(t,r,n){return this._def(ti.varKinds.let,t,r,n)}var(t,r,n){return this._def(ti.varKinds.var,t,r,n)}assign(t,r,n){return this._leafNode(new Vm(t,r,n))}add(t,r){return this._leafNode(new Uk(t,Ne.operators.ADD,r))}code(t){return typeof t=="function"?t():t!==Oe.nil&&this._leafNode(new Gk(t)),this}object(...t){let r=["{"];for(let[n,i]of t)r.length>1&&r.push(","),r.push(n),(n!==i||this.opts.es5)&&(r.push(":"),(0,Oe.addCodeArg)(r,i));return r.push("}"),new Oe._Code(r)}if(t,r,n){if(this._blockNode(new Za(t)),r&&n)this.code(r).else().code(n).endIf();else if(r)this.code(r).endIf();else if(n)throw new Error('CodeGen: "else" body without "then" body');return this}elseIf(t){return this._elseNode(new Za(t))}else(){return this._elseNode(new _c)}endIf(){return this._endBlockNode(Za,_c)}_for(t,r){return this._blockNode(t),r&&this.code(r).endFor(),this}for(t,r){return this._for(new Xk(t),r)}forRange(t,r,n,i,o=this.opts.es5?ti.varKinds.var:ti.varKinds.let){let a=this._scope.toName(t);return this._for(new Zk(o,a,r,n),()=>i(a))}forOf(t,r,n,i=ti.varKinds.const){let o=this._scope.toName(t);if(this.opts.es5){let a=r instanceof Oe.Name?r:this.var("_arr",r);return this.forRange("_i",0,(0,Oe._)`${a}.length`,s=>{this.var(o,(0,Oe._)`${a}[${s}]`),n(o)})}return this._for(new Mm("of",i,o,r),()=>n(o))}forIn(t,r,n,i=this.opts.es5?ti.varKinds.var:ti.varKinds.const){if(this.opts.ownProperties)return this.forOf(t,(0,Oe._)`Object.keys(${r})`,n);let o=this._scope.toName(t);return this._for(new Mm("in",i,o,r),()=>n(o))}endFor(){return this._endBlockNode(es)}label(t){return this._leafNode(new Jk(t))}break(t){return this._leafNode(new zk(t))}return(t){let r=new id;if(this._blockNode(r),this.code(t),r.nodes.length!==1)throw new Error('CodeGen: "return" should have one node');return this._endBlockNode(id)}try(t,r,n){if(!r&&!n)throw new Error('CodeGen: "try" without "catch" and "finally"');let i=new eb;if(this._blockNode(i),this.code(t),r){let o=this.name("e");this._currNode=i.catch=new od(o),r(o)}return n&&(this._currNode=i.finally=new ad,this.code(n)),this._endBlockNode(od,ad)}throw(t){return this._leafNode(new Kk(t))}block(t,r){return this._blockStarts.push(this._nodes.length),t&&this.code(t).endBlock(r),this}endBlock(t){let r=this._blockStarts.pop();if(r===void 0)throw new Error("CodeGen: not in self-balancing block");let n=this._nodes.length-r;if(n<0||t!==void 0&&n!==t)throw new Error(`CodeGen: wrong number of nodes: ${n} vs ${t} expected`);return this._nodes.length=r,this}func(t,r=Oe.nil,n,i){return this._blockNode(new nd(t,r,n)),i&&this.code(i).endFunc(),this}endFunc(){return this._endBlockNode(nd)}optimize(t=1){for(;t-- >0;)this._root.optimizeNodes(),this._root.optimizeNames(this._root.names,this._constants)}_leafNode(t){return this._currNode.nodes.push(t),this}_blockNode(t){this._currNode.nodes.push(t),this._nodes.push(t)}_endBlockNode(t,r){let n=this._currNode;if(n instanceof t||r&&n instanceof r)return this._nodes.pop(),this;throw new Error(`CodeGen: not in block "${r?`${t.kind}/${r.kind}`:t.kind}"`)}_elseNode(t){let r=this._currNode;if(!(r instanceof Za))throw new Error('CodeGen: "else" without "if"');return this._currNode=r.else=t,this}get _root(){return this._nodes[0]}get _currNode(){let t=this._nodes;return t[t.length-1]}set _currNode(t){let r=this._nodes;r[r.length-1]=t}};Ne.CodeGen=tb;function ts(e,t){for(let r in t)e[r]=(e[r]||0)+(t[r]||0);return e}function Fm(e,t){return t instanceof Oe._CodeOrName?ts(e,t.names):e}function Ic(e,t,r){if(e instanceof Oe.Name)return n(e);if(!i(e))return e;return new Oe._Code(e._items.reduce((o,a)=>(a instanceof Oe.Name&&(a=n(a)),a instanceof Oe._Code?o.push(...a._items):o.push(a),o),[]));function n(o){let a=r[o.str];return a===void 0||t[o.str]!==1?o:(delete t[o.str],a)}function i(o){return o instanceof Oe._Code&&o._items.some(a=>a instanceof Oe.Name&&t[a.str]===1&&r[a.str]!==void 0)}}function mU(e,t){for(let r in t)e[r]=(e[r]||0)-(t[r]||0)}function Xx(e){return typeof e=="boolean"||typeof e=="number"||e===null?!e:(0,Oe._)`!${rb(e)}`}Ne.not=Xx;var hU=Zx(Ne.operators.AND);function gU(...e){return e.reduce(hU)}Ne.and=gU;var vU=Zx(Ne.operators.OR);function wU(...e){return e.reduce(vU)}Ne.or=wU;function Zx(e){return(t,r)=>t===Oe.nil?r:r===Oe.nil?t:(0,Oe._)`${rb(t)} ${e} ${rb(r)}`}function rb(e){return e instanceof Oe.Name?e:(0,Oe._)`(${e})`}});var Be=$(_e=>{"use strict";Object.defineProperty(_e,"__esModule",{value:!0});_e.checkStrictMode=_e.getErrorPath=_e.Type=_e.useFunc=_e.setEvaluated=_e.evaluatedPropsToName=_e.mergeEvaluated=_e.eachItem=_e.unescapeJsonPointer=_e.escapeJsonPointer=_e.escapeFragment=_e.unescapeFragment=_e.schemaRefOrVal=_e.schemaHasRulesButRef=_e.schemaHasRules=_e.checkUnknownRules=_e.alwaysValidSchema=_e.toHash=void 0;var et=Ce(),yU=td();function kU(e){let t={};for(let r of e)t[r]=!0;return t}_e.toHash=kU;function bU(e,t){return typeof t=="boolean"?t:Object.keys(t).length===0?!0:(rP(e,t),!nP(t,e.self.RULES.all))}_e.alwaysValidSchema=bU;function rP(e,t=e.schema){let{opts:r,self:n}=e;if(!r.strictSchema||typeof t=="boolean")return;let i=n.RULES.keywords;for(let o in t)i[o]||aP(e,`unknown keyword: "${o}"`)}_e.checkUnknownRules=rP;function nP(e,t){if(typeof e=="boolean")return!e;for(let r in e)if(t[r])return!0;return!1}_e.schemaHasRules=nP;function AU(e,t){if(typeof e=="boolean")return!e;for(let r in e)if(r!=="$ref"&&t.all[r])return!0;return!1}_e.schemaHasRulesButRef=AU;function RU({topSchemaRef:e,schemaPath:t},r,n,i){if(!i){if(typeof r=="number"||typeof r=="boolean")return r;if(typeof r=="string")return(0,et._)`${r}`}return(0,et._)`${e}${t}${(0,et.getProperty)(n)}`}_e.schemaRefOrVal=RU;function NU(e){return iP(decodeURIComponent(e))}_e.unescapeFragment=NU;function SU(e){return encodeURIComponent(ib(e))}_e.escapeFragment=SU;function ib(e){return typeof e=="number"?`${e}`:e.replace(/~/g,"~0").replace(/\//g,"~1")}_e.escapeJsonPointer=ib;function iP(e){return e.replace(/~1/g,"/").replace(/~0/g,"~")}_e.unescapeJsonPointer=iP;function EU(e,t){if(Array.isArray(e))for(let r of e)t(r);else t(e)}_e.eachItem=EU;function eP({mergeNames:e,mergeToName:t,mergeValues:r,resultToName:n}){return(i,o,a,s)=>{let c=a===void 0?o:a instanceof et.Name?(o instanceof et.Name?e(i,o,a):t(i,o,a),a):o instanceof et.Name?(t(i,a,o),o):r(o,a);return s===et.Name&&!(c instanceof et.Name)?n(i,c):c}}_e.mergeEvaluated={props:eP({mergeNames:(e,t,r)=>e.if((0,et._)`${r} !== true && ${t} !== undefined`,()=>{e.if((0,et._)`${t} === true`,()=>e.assign(r,!0),()=>e.assign(r,(0,et._)`${r} || {}`).code((0,et._)`Object.assign(${r}, ${t})`))}),mergeToName:(e,t,r)=>e.if((0,et._)`${r} !== true`,()=>{t===!0?e.assign(r,!0):(e.assign(r,(0,et._)`${r} || {}`),ob(e,r,t))}),mergeValues:(e,t)=>e===!0?!0:{...e,...t},resultToName:oP}),items:eP({mergeNames:(e,t,r)=>e.if((0,et._)`${r} !== true && ${t} !== undefined`,()=>e.assign(r,(0,et._)`${t} === true ? true : ${r} > ${t} ? ${r} : ${t}`)),mergeToName:(e,t,r)=>e.if((0,et._)`${r} !== true`,()=>e.assign(r,t===!0?!0:(0,et._)`${r} > ${t} ? ${r} : ${t}`)),mergeValues:(e,t)=>e===!0?!0:Math.max(e,t),resultToName:(e,t)=>e.var("items",t)})};function oP(e,t){if(t===!0)return e.var("props",!0);let r=e.var("props",(0,et._)`{}`);return t!==void 0&&ob(e,r,t),r}_e.evaluatedPropsToName=oP;function ob(e,t,r){Object.keys(r).forEach(n=>e.assign((0,et._)`${t}${(0,et.getProperty)(n)}`,!0))}_e.setEvaluated=ob;var tP={};function CU(e,t){return e.scopeValue("func",{ref:t,code:tP[t.code]||(tP[t.code]=new yU._Code(t.code))})}_e.useFunc=CU;var nb;(function(e){e[e.Num=0]="Num",e[e.Str=1]="Str"})(nb||(_e.Type=nb={}));function _U(e,t,r){if(e instanceof et.Name){let n=t===nb.Num;return r?n?(0,et._)`"[" + ${e} + "]"`:(0,et._)`"['" + ${e} + "']"`:n?(0,et._)`"/" + ${e}`:(0,et._)`"/" + ${e}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return r?(0,et.getProperty)(e).toString():"/"+ib(e)}_e.getErrorPath=_U;function aP(e,t,r=e.opts.strictSchema){if(r){if(t=`strict mode: ${t}`,r===!0)throw new Error(t);e.self.logger.warn(t)}}_e.checkStrictMode=aP});var co=$(ab=>{"use strict";Object.defineProperty(ab,"__esModule",{value:!0});var pr=Ce(),IU={data:new pr.Name("data"),valCxt:new pr.Name("valCxt"),instancePath:new pr.Name("instancePath"),parentData:new pr.Name("parentData"),parentDataProperty:new pr.Name("parentDataProperty"),rootData:new pr.Name("rootData"),dynamicAnchors:new pr.Name("dynamicAnchors"),vErrors:new pr.Name("vErrors"),errors:new pr.Name("errors"),this:new pr.Name("this"),self:new pr.Name("self"),scope:new pr.Name("scope"),json:new pr.Name("json"),jsonPos:new pr.Name("jsonPos"),jsonLen:new pr.Name("jsonLen"),jsonPart:new pr.Name("jsonPart")};ab.default=IU});var sd=$(mr=>{"use strict";Object.defineProperty(mr,"__esModule",{value:!0});mr.extendErrors=mr.resetErrorsCount=mr.reportExtraError=mr.reportError=mr.keyword$DataError=mr.keywordError=void 0;var We=Ce(),Qm=Be(),Tr=co();mr.keywordError={message:({keyword:e})=>(0,We.str)`must pass "${e}" keyword validation`};mr.keyword$DataError={message:({keyword:e,schemaType:t})=>t?(0,We.str)`"${e}" keyword must be ${t} ($data)`:(0,We.str)`"${e}" keyword is invalid ($data)`};function xU(e,t=mr.keywordError,r,n){let{it:i}=e,{gen:o,compositeRule:a,allErrors:s}=i,c=lP(e,t,r);n??(a||s)?sP(o,c):cP(i,(0,We._)`[${c}]`)}mr.reportError=xU;function PU(e,t=mr.keywordError,r){let{it:n}=e,{gen:i,compositeRule:o,allErrors:a}=n,s=lP(e,t,r);sP(i,s),o||a||cP(n,Tr.default.vErrors)}mr.reportExtraError=PU;function TU(e,t){e.assign(Tr.default.errors,t),e.if((0,We._)`${Tr.default.vErrors} !== null`,()=>e.if(t,()=>e.assign((0,We._)`${Tr.default.vErrors}.length`,t),()=>e.assign(Tr.default.vErrors,null)))}mr.resetErrorsCount=TU;function OU({gen:e,keyword:t,schemaValue:r,data:n,errsCount:i,it:o}){if(i===void 0)throw new Error("ajv implementation error");let a=e.name("err");e.forRange("i",i,Tr.default.errors,s=>{e.const(a,(0,We._)`${Tr.default.vErrors}[${s}]`),e.if((0,We._)`${a}.instancePath === undefined`,()=>e.assign((0,We._)`${a}.instancePath`,(0,We.strConcat)(Tr.default.instancePath,o.errorPath))),e.assign((0,We._)`${a}.schemaPath`,(0,We.str)`${o.errSchemaPath}/${t}`),o.opts.verbose&&(e.assign((0,We._)`${a}.schema`,r),e.assign((0,We._)`${a}.data`,n))})}mr.extendErrors=OU;function sP(e,t){let r=e.const("err",t);e.if((0,We._)`${Tr.default.vErrors} === null`,()=>e.assign(Tr.default.vErrors,(0,We._)`[${r}]`),(0,We._)`${Tr.default.vErrors}.push(${r})`),e.code((0,We._)`${Tr.default.errors}++`)}function cP(e,t){let{gen:r,validateName:n,schemaEnv:i}=e;i.$async?r.throw((0,We._)`new ${e.ValidationError}(${t})`):(r.assign((0,We._)`${n}.errors`,t),r.return(!1))}var rs={keyword:new We.Name("keyword"),schemaPath:new We.Name("schemaPath"),params:new We.Name("params"),propertyName:new We.Name("propertyName"),message:new We.Name("message"),schema:new We.Name("schema"),parentSchema:new We.Name("parentSchema")};function lP(e,t,r){let{createErrors:n}=e.it;return n===!1?(0,We._)`{}`:jU(e,t,r)}function jU(e,t,r={}){let{gen:n,it:i}=e,o=[$U(i,r),DU(e,r)];return BU(e,t,o),n.object(...o)}function $U({errorPath:e},{instancePath:t}){let r=t?(0,We.str)`${e}${(0,Qm.getErrorPath)(t,Qm.Type.Str)}`:e;return[Tr.default.instancePath,(0,We.strConcat)(Tr.default.instancePath,r)]}function DU({keyword:e,it:{errSchemaPath:t}},{schemaPath:r,parentSchema:n}){let i=n?t:(0,We.str)`${t}/${e}`;return r&&(i=(0,We.str)`${i}${(0,Qm.getErrorPath)(r,Qm.Type.Str)}`),[rs.schemaPath,i]}function BU(e,{params:t,message:r},n){let{keyword:i,data:o,schemaValue:a,it:s}=e,{opts:c,propertyName:l,topSchemaRef:u,schemaPath:f}=s;n.push([rs.keyword,i],[rs.params,typeof t=="function"?t(e):t||(0,We._)`{}`]),c.messages&&n.push([rs.message,typeof r=="function"?r(e):r]),c.verbose&&n.push([rs.schema,a],[rs.parentSchema,(0,We._)`${u}${f}`],[Tr.default.data,o]),l&&n.push([rs.propertyName,l])}});var dP=$(xc=>{"use strict";Object.defineProperty(xc,"__esModule",{value:!0});xc.boolOrEmptySchema=xc.topBoolOrEmptySchema=void 0;var WU=sd(),qU=Ce(),LU=co(),VU={message:"boolean schema is false"};function MU(e){let{gen:t,schema:r,validateName:n}=e;r===!1?uP(e,!1):typeof r=="object"&&r.$async===!0?t.return(LU.default.data):(t.assign((0,qU._)`${n}.errors`,null),t.return(!0))}xc.topBoolOrEmptySchema=MU;function FU(e,t){let{gen:r,schema:n}=e;n===!1?(r.var(t,!1),uP(e)):r.var(t,!0)}xc.boolOrEmptySchema=FU;function uP(e,t){let{gen:r,data:n}=e,i={gen:r,keyword:"false schema",data:n,schema:!1,schemaCode:!1,schemaValue:!1,params:{},it:e};(0,WU.reportError)(i,VU,void 0,t)}});var sb=$(Pc=>{"use strict";Object.defineProperty(Pc,"__esModule",{value:!0});Pc.getRules=Pc.isJSONType=void 0;var HU=["string","number","integer","boolean","null","object","array"],QU=new Set(HU);function UU(e){return typeof e=="string"&&QU.has(e)}Pc.isJSONType=UU;function JU(){let e={number:{type:"number",rules:[]},string:{type:"string",rules:[]},array:{type:"array",rules:[]},object:{type:"object",rules:[]}};return{types:{...e,integer:!0,boolean:!0,null:!0},rules:[{rules:[]},e.number,e.string,e.array,e.object],post:{rules:[]},all:{},keywords:{}}}Pc.getRules=JU});var cb=$(na=>{"use strict";Object.defineProperty(na,"__esModule",{value:!0});na.shouldUseRule=na.shouldUseGroup=na.schemaHasRulesForType=void 0;function zU({schema:e,self:t},r){let n=t.RULES.types[r];return n&&n!==!0&&fP(e,n)}na.schemaHasRulesForType=zU;function fP(e,t){return t.rules.some(r=>pP(e,r))}na.shouldUseGroup=fP;function pP(e,t){var r;return e[t.keyword]!==void 0||((r=t.definition.implements)===null||r===void 0?void 0:r.some(n=>e[n]!==void 0))}na.shouldUseRule=pP});var cd=$(hr=>{"use strict";Object.defineProperty(hr,"__esModule",{value:!0});hr.reportTypeError=hr.checkDataTypes=hr.checkDataType=hr.coerceAndCheckDataType=hr.getJSONTypes=hr.getSchemaTypes=hr.DataType=void 0;var KU=sb(),GU=cb(),YU=sd(),be=Ce(),mP=Be(),Tc;(function(e){e[e.Correct=0]="Correct",e[e.Wrong=1]="Wrong"})(Tc||(hr.DataType=Tc={}));function XU(e){let t=hP(e.type);if(t.includes("null")){if(e.nullable===!1)throw new Error("type: null contradicts nullable: false")}else{if(!t.length&&e.nullable!==void 0)throw new Error('"nullable" cannot be used without "type"');e.nullable===!0&&t.push("null")}return t}hr.getSchemaTypes=XU;function hP(e){let t=Array.isArray(e)?e:e?[e]:[];if(t.every(KU.isJSONType))return t;throw new Error("type must be JSONType or JSONType[]: "+t.join(","))}hr.getJSONTypes=hP;function ZU(e,t){let{gen:r,data:n,opts:i}=e,o=eJ(t,i.coerceTypes),a=t.length>0&&!(o.length===0&&t.length===1&&(0,GU.schemaHasRulesForType)(e,t[0]));if(a){let s=ub(t,n,i.strictNumbers,Tc.Wrong);r.if(s,()=>{o.length?tJ(e,t,o):db(e)})}return a}hr.coerceAndCheckDataType=ZU;var gP=new Set(["string","number","integer","boolean","null"]);function eJ(e,t){return t?e.filter(r=>gP.has(r)||t==="array"&&r==="array"):[]}function tJ(e,t,r){let{gen:n,data:i,opts:o}=e,a=n.let("dataType",(0,be._)`typeof ${i}`),s=n.let("coerced",(0,be._)`undefined`);o.coerceTypes==="array"&&n.if((0,be._)`${a} == 'object' && Array.isArray(${i}) && ${i}.length == 1`,()=>n.assign(i,(0,be._)`${i}[0]`).assign(a,(0,be._)`typeof ${i}`).if(ub(t,i,o.strictNumbers),()=>n.assign(s,i))),n.if((0,be._)`${s} !== undefined`);for(let l of r)(gP.has(l)||l==="array"&&o.coerceTypes==="array")&&c(l);n.else(),db(e),n.endIf(),n.if((0,be._)`${s} !== undefined`,()=>{n.assign(i,s),rJ(e,s)});function c(l){switch(l){case"string":n.elseIf((0,be._)`${a} == "number" || ${a} == "boolean"`).assign(s,(0,be._)`"" + ${i}`).elseIf((0,be._)`${i} === null`).assign(s,(0,be._)`""`);return;case"number":n.elseIf((0,be._)`${a} == "boolean" || ${i} === null
|
|
189
|
+
|| (${a} == "string" && ${i} && ${i} == +${i})`).assign(s,(0,be._)`+${i}`);return;case"integer":n.elseIf((0,be._)`${a} === "boolean" || ${i} === null
|
|
190
|
+
|| (${a} === "string" && ${i} && ${i} == +${i} && !(${i} % 1))`).assign(s,(0,be._)`+${i}`);return;case"boolean":n.elseIf((0,be._)`${i} === "false" || ${i} === 0 || ${i} === null`).assign(s,!1).elseIf((0,be._)`${i} === "true" || ${i} === 1`).assign(s,!0);return;case"null":n.elseIf((0,be._)`${i} === "" || ${i} === 0 || ${i} === false`),n.assign(s,null);return;case"array":n.elseIf((0,be._)`${a} === "string" || ${a} === "number"
|
|
191
|
+
|| ${a} === "boolean" || ${i} === null`).assign(s,(0,be._)`[${i}]`)}}}function rJ({gen:e,parentData:t,parentDataProperty:r},n){e.if((0,be._)`${t} !== undefined`,()=>e.assign((0,be._)`${t}[${r}]`,n))}function lb(e,t,r,n=Tc.Correct){let i=n===Tc.Correct?be.operators.EQ:be.operators.NEQ,o;switch(e){case"null":return(0,be._)`${t} ${i} null`;case"array":o=(0,be._)`Array.isArray(${t})`;break;case"object":o=(0,be._)`${t} && typeof ${t} == "object" && !Array.isArray(${t})`;break;case"integer":o=a((0,be._)`!(${t} % 1) && !isNaN(${t})`);break;case"number":o=a();break;default:return(0,be._)`typeof ${t} ${i} ${e}`}return n===Tc.Correct?o:(0,be.not)(o);function a(s=be.nil){return(0,be.and)((0,be._)`typeof ${t} == "number"`,s,r?(0,be._)`isFinite(${t})`:be.nil)}}hr.checkDataType=lb;function ub(e,t,r,n){if(e.length===1)return lb(e[0],t,r,n);let i,o=(0,mP.toHash)(e);if(o.array&&o.object){let a=(0,be._)`typeof ${t} != "object"`;i=o.null?a:(0,be._)`!${t} || ${a}`,delete o.null,delete o.array,delete o.object}else i=be.nil;o.number&&delete o.integer;for(let a in o)i=(0,be.and)(i,lb(a,t,r,n));return i}hr.checkDataTypes=ub;var nJ={message:({schema:e})=>`must be ${e}`,params:({schema:e,schemaValue:t})=>typeof e=="string"?(0,be._)`{type: ${e}}`:(0,be._)`{type: ${t}}`};function db(e){let t=iJ(e);(0,YU.reportError)(t,nJ)}hr.reportTypeError=db;function iJ(e){let{gen:t,data:r,schema:n}=e,i=(0,mP.schemaRefOrVal)(e,n,"type");return{gen:t,keyword:"type",data:r,schema:n.type,schemaCode:i,schemaValue:i,parentSchema:n,params:{},it:e}}});var wP=$(Um=>{"use strict";Object.defineProperty(Um,"__esModule",{value:!0});Um.assignDefaults=void 0;var Oc=Ce(),oJ=Be();function aJ(e,t){let{properties:r,items:n}=e.schema;if(t==="object"&&r)for(let i in r)vP(e,i,r[i].default);else t==="array"&&Array.isArray(n)&&n.forEach((i,o)=>vP(e,o,i.default))}Um.assignDefaults=aJ;function vP(e,t,r){let{gen:n,compositeRule:i,data:o,opts:a}=e;if(r===void 0)return;let s=(0,Oc._)`${o}${(0,Oc.getProperty)(t)}`;if(i){(0,oJ.checkStrictMode)(e,`default is ignored for: ${s}`);return}let c=(0,Oc._)`${s} === undefined`;a.useDefaults==="empty"&&(c=(0,Oc._)`${c} || ${s} === null || ${s} === ""`),n.if(c,(0,Oc._)`${s} = ${(0,Oc.stringify)(r)}`)}});var jn=$(Ze=>{"use strict";Object.defineProperty(Ze,"__esModule",{value:!0});Ze.validateUnion=Ze.validateArray=Ze.usePattern=Ze.callValidateCode=Ze.schemaProperties=Ze.allSchemaProperties=Ze.noPropertyInData=Ze.propertyInData=Ze.isOwnProperty=Ze.hasPropFunc=Ze.reportMissingProp=Ze.checkMissingProp=Ze.checkReportMissingProp=void 0;var st=Ce(),fb=Be(),ia=co(),sJ=Be();function cJ(e,t){let{gen:r,data:n,it:i}=e;r.if(mb(r,n,t,i.opts.ownProperties),()=>{e.setParams({missingProperty:(0,st._)`${t}`},!0),e.error()})}Ze.checkReportMissingProp=cJ;function lJ({gen:e,data:t,it:{opts:r}},n,i){return(0,st.or)(...n.map(o=>(0,st.and)(mb(e,t,o,r.ownProperties),(0,st._)`${i} = ${o}`)))}Ze.checkMissingProp=lJ;function uJ(e,t){e.setParams({missingProperty:t},!0),e.error()}Ze.reportMissingProp=uJ;function yP(e){return e.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:(0,st._)`Object.prototype.hasOwnProperty`})}Ze.hasPropFunc=yP;function pb(e,t,r){return(0,st._)`${yP(e)}.call(${t}, ${r})`}Ze.isOwnProperty=pb;function dJ(e,t,r,n){let i=(0,st._)`${t}${(0,st.getProperty)(r)} !== undefined`;return n?(0,st._)`${i} && ${pb(e,t,r)}`:i}Ze.propertyInData=dJ;function mb(e,t,r,n){let i=(0,st._)`${t}${(0,st.getProperty)(r)} === undefined`;return n?(0,st.or)(i,(0,st.not)(pb(e,t,r))):i}Ze.noPropertyInData=mb;function kP(e){return e?Object.keys(e).filter(t=>t!=="__proto__"):[]}Ze.allSchemaProperties=kP;function fJ(e,t){return kP(t).filter(r=>!(0,fb.alwaysValidSchema)(e,t[r]))}Ze.schemaProperties=fJ;function pJ({schemaCode:e,data:t,it:{gen:r,topSchemaRef:n,schemaPath:i,errorPath:o},it:a},s,c,l){let u=l?(0,st._)`${e}, ${t}, ${n}${i}`:t,f=[[ia.default.instancePath,(0,st.strConcat)(ia.default.instancePath,o)],[ia.default.parentData,a.parentData],[ia.default.parentDataProperty,a.parentDataProperty],[ia.default.rootData,ia.default.rootData]];a.opts.dynamicRef&&f.push([ia.default.dynamicAnchors,ia.default.dynamicAnchors]);let d=(0,st._)`${u}, ${r.object(...f)}`;return c!==st.nil?(0,st._)`${s}.call(${c}, ${d})`:(0,st._)`${s}(${d})`}Ze.callValidateCode=pJ;var mJ=(0,st._)`new RegExp`;function hJ({gen:e,it:{opts:t}},r){let n=t.unicodeRegExp?"u":"",{regExp:i}=t.code,o=i(r,n);return e.scopeValue("pattern",{key:o.toString(),ref:o,code:(0,st._)`${i.code==="new RegExp"?mJ:(0,sJ.useFunc)(e,i)}(${r}, ${n})`})}Ze.usePattern=hJ;function gJ(e){let{gen:t,data:r,keyword:n,it:i}=e,o=t.name("valid");if(i.allErrors){let s=t.let("valid",!0);return a(()=>t.assign(s,!1)),s}return t.var(o,!0),a(()=>t.break()),o;function a(s){let c=t.const("len",(0,st._)`${r}.length`);t.forRange("i",0,c,l=>{e.subschema({keyword:n,dataProp:l,dataPropType:fb.Type.Num},o),t.if((0,st.not)(o),s)})}}Ze.validateArray=gJ;function vJ(e){let{gen:t,schema:r,keyword:n,it:i}=e;if(!Array.isArray(r))throw new Error("ajv implementation error");if(r.some(c=>(0,fb.alwaysValidSchema)(i,c))&&!i.opts.unevaluated)return;let a=t.let("valid",!1),s=t.name("_valid");t.block(()=>r.forEach((c,l)=>{let u=e.subschema({keyword:n,schemaProp:l,compositeRule:!0},s);t.assign(a,(0,st._)`${a} || ${s}`),e.mergeValidEvaluated(u,s)||t.if((0,st.not)(a))})),e.result(a,()=>e.reset(),()=>e.error(!0))}Ze.validateUnion=vJ});var RP=$(_i=>{"use strict";Object.defineProperty(_i,"__esModule",{value:!0});_i.validateKeywordUsage=_i.validSchemaType=_i.funcKeywordCode=_i.macroKeywordCode=void 0;var Or=Ce(),ns=co(),wJ=jn(),yJ=sd();function kJ(e,t){let{gen:r,keyword:n,schema:i,parentSchema:o,it:a}=e,s=t.macro.call(a.self,i,o,a),c=AP(r,n,s);a.opts.validateSchema!==!1&&a.self.validateSchema(s,!0);let l=r.name("valid");e.subschema({schema:s,schemaPath:Or.nil,errSchemaPath:`${a.errSchemaPath}/${n}`,topSchemaRef:c,compositeRule:!0},l),e.pass(l,()=>e.error(!0))}_i.macroKeywordCode=kJ;function bJ(e,t){var r;let{gen:n,keyword:i,schema:o,parentSchema:a,$data:s,it:c}=e;RJ(c,t);let l=!s&&t.compile?t.compile.call(c.self,o,a,c):t.validate,u=AP(n,i,l),f=n.let("valid");e.block$data(f,d),e.ok((r=t.valid)!==null&&r!==void 0?r:f);function d(){if(t.errors===!1)h(),t.modifying&&bP(e),g(()=>e.error());else{let v=t.async?p():m();t.modifying&&bP(e),g(()=>AJ(e,v))}}function p(){let v=n.let("ruleErrs",null);return n.try(()=>h((0,Or._)`await `),w=>n.assign(f,!1).if((0,Or._)`${w} instanceof ${c.ValidationError}`,()=>n.assign(v,(0,Or._)`${w}.errors`),()=>n.throw(w))),v}function m(){let v=(0,Or._)`${u}.errors`;return n.assign(v,null),h(Or.nil),v}function h(v=t.async?(0,Or._)`await `:Or.nil){let w=c.opts.passContext?ns.default.this:ns.default.self,y=!("compile"in t&&!s||t.schema===!1);n.assign(f,(0,Or._)`${v}${(0,wJ.callValidateCode)(e,u,w,y)}`,t.modifying)}function g(v){var w;n.if((0,Or.not)((w=t.valid)!==null&&w!==void 0?w:f),v)}}_i.funcKeywordCode=bJ;function bP(e){let{gen:t,data:r,it:n}=e;t.if(n.parentData,()=>t.assign(r,(0,Or._)`${n.parentData}[${n.parentDataProperty}]`))}function AJ(e,t){let{gen:r}=e;r.if((0,Or._)`Array.isArray(${t})`,()=>{r.assign(ns.default.vErrors,(0,Or._)`${ns.default.vErrors} === null ? ${t} : ${ns.default.vErrors}.concat(${t})`).assign(ns.default.errors,(0,Or._)`${ns.default.vErrors}.length`),(0,yJ.extendErrors)(e)},()=>e.error())}function RJ({schemaEnv:e},t){if(t.async&&!e.$async)throw new Error("async keyword in sync schema")}function AP(e,t,r){if(r===void 0)throw new Error(`keyword "${t}" failed to compile`);return e.scopeValue("keyword",typeof r=="function"?{ref:r}:{ref:r,code:(0,Or.stringify)(r)})}function NJ(e,t,r=!1){return!t.length||t.some(n=>n==="array"?Array.isArray(e):n==="object"?e&&typeof e=="object"&&!Array.isArray(e):typeof e==n||r&&typeof e>"u")}_i.validSchemaType=NJ;function SJ({schema:e,opts:t,self:r,errSchemaPath:n},i,o){if(Array.isArray(i.keyword)?!i.keyword.includes(o):i.keyword!==o)throw new Error("ajv implementation error");let a=i.dependencies;if(a?.some(s=>!Object.prototype.hasOwnProperty.call(e,s)))throw new Error(`parent schema must have dependencies of ${o}: ${a.join(",")}`);if(i.validateSchema&&!i.validateSchema(e[o])){let c=`keyword "${o}" value is invalid at path "${n}": `+r.errorsText(i.validateSchema.errors);if(t.validateSchema==="log")r.logger.error(c);else throw new Error(c)}}_i.validateKeywordUsage=SJ});var SP=$(oa=>{"use strict";Object.defineProperty(oa,"__esModule",{value:!0});oa.extendSubschemaMode=oa.extendSubschemaData=oa.getSubschema=void 0;var Ii=Ce(),NP=Be();function EJ(e,{keyword:t,schemaProp:r,schema:n,schemaPath:i,errSchemaPath:o,topSchemaRef:a}){if(t!==void 0&&n!==void 0)throw new Error('both "keyword" and "schema" passed, only one allowed');if(t!==void 0){let s=e.schema[t];return r===void 0?{schema:s,schemaPath:(0,Ii._)`${e.schemaPath}${(0,Ii.getProperty)(t)}`,errSchemaPath:`${e.errSchemaPath}/${t}`}:{schema:s[r],schemaPath:(0,Ii._)`${e.schemaPath}${(0,Ii.getProperty)(t)}${(0,Ii.getProperty)(r)}`,errSchemaPath:`${e.errSchemaPath}/${t}/${(0,NP.escapeFragment)(r)}`}}if(n!==void 0){if(i===void 0||o===void 0||a===void 0)throw new Error('"schemaPath", "errSchemaPath" and "topSchemaRef" are required with "schema"');return{schema:n,schemaPath:i,topSchemaRef:a,errSchemaPath:o}}throw new Error('either "keyword" or "schema" must be passed')}oa.getSubschema=EJ;function CJ(e,t,{dataProp:r,dataPropType:n,data:i,dataTypes:o,propertyName:a}){if(i!==void 0&&r!==void 0)throw new Error('both "data" and "dataProp" passed, only one allowed');let{gen:s}=t;if(r!==void 0){let{errorPath:l,dataPathArr:u,opts:f}=t,d=s.let("data",(0,Ii._)`${t.data}${(0,Ii.getProperty)(r)}`,!0);c(d),e.errorPath=(0,Ii.str)`${l}${(0,NP.getErrorPath)(r,n,f.jsPropertySyntax)}`,e.parentDataProperty=(0,Ii._)`${r}`,e.dataPathArr=[...u,e.parentDataProperty]}if(i!==void 0){let l=i instanceof Ii.Name?i:s.let("data",i,!0);c(l),a!==void 0&&(e.propertyName=a)}o&&(e.dataTypes=o);function c(l){e.data=l,e.dataLevel=t.dataLevel+1,e.dataTypes=[],t.definedProperties=new Set,e.parentData=t.data,e.dataNames=[...t.dataNames,l]}}oa.extendSubschemaData=CJ;function _J(e,{jtdDiscriminator:t,jtdMetadata:r,compositeRule:n,createErrors:i,allErrors:o}){n!==void 0&&(e.compositeRule=n),i!==void 0&&(e.createErrors=i),o!==void 0&&(e.allErrors=o),e.jtdDiscriminator=t,e.jtdMetadata=r}oa.extendSubschemaMode=_J});var hb=$((une,EP)=>{"use strict";EP.exports=function e(t,r){if(t===r)return!0;if(t&&r&&typeof t=="object"&&typeof r=="object"){if(t.constructor!==r.constructor)return!1;var n,i,o;if(Array.isArray(t)){if(n=t.length,n!=r.length)return!1;for(i=n;i--!==0;)if(!e(t[i],r[i]))return!1;return!0}if(t.constructor===RegExp)return t.source===r.source&&t.flags===r.flags;if(t.valueOf!==Object.prototype.valueOf)return t.valueOf()===r.valueOf();if(t.toString!==Object.prototype.toString)return t.toString()===r.toString();if(o=Object.keys(t),n=o.length,n!==Object.keys(r).length)return!1;for(i=n;i--!==0;)if(!Object.prototype.hasOwnProperty.call(r,o[i]))return!1;for(i=n;i--!==0;){var a=o[i];if(!e(t[a],r[a]))return!1}return!0}return t!==t&&r!==r}});var _P=$((dne,CP)=>{"use strict";var aa=CP.exports=function(e,t,r){typeof t=="function"&&(r=t,t={}),r=t.cb||r;var n=typeof r=="function"?r:r.pre||function(){},i=r.post||function(){};Jm(t,n,i,e,"",e)};aa.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0};aa.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0};aa.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0};aa.skipKeywords={default:!0,enum:!0,const:!0,required:!0,maximum:!0,minimum:!0,exclusiveMaximum:!0,exclusiveMinimum:!0,multipleOf:!0,maxLength:!0,minLength:!0,pattern:!0,format:!0,maxItems:!0,minItems:!0,uniqueItems:!0,maxProperties:!0,minProperties:!0};function Jm(e,t,r,n,i,o,a,s,c,l){if(n&&typeof n=="object"&&!Array.isArray(n)){t(n,i,o,a,s,c,l);for(var u in n){var f=n[u];if(Array.isArray(f)){if(u in aa.arrayKeywords)for(var d=0;d<f.length;d++)Jm(e,t,r,f[d],i+"/"+u+"/"+d,o,i,u,n,d)}else if(u in aa.propsKeywords){if(f&&typeof f=="object")for(var p in f)Jm(e,t,r,f[p],i+"/"+u+"/"+IJ(p),o,i,u,n,p)}else(u in aa.keywords||e.allKeys&&!(u in aa.skipKeywords))&&Jm(e,t,r,f,i+"/"+u,o,i,u,n)}r(n,i,o,a,s,c,l)}}function IJ(e){return e.replace(/~/g,"~0").replace(/\//g,"~1")}});var ld=$(Xr=>{"use strict";Object.defineProperty(Xr,"__esModule",{value:!0});Xr.getSchemaRefs=Xr.resolveUrl=Xr.normalizeId=Xr._getFullPath=Xr.getFullPath=Xr.inlineRef=void 0;var xJ=Be(),PJ=hb(),TJ=_P(),OJ=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);function jJ(e,t=!0){return typeof e=="boolean"?!0:t===!0?!gb(e):t?IP(e)<=t:!1}Xr.inlineRef=jJ;var $J=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function gb(e){for(let t in e){if($J.has(t))return!0;let r=e[t];if(Array.isArray(r)&&r.some(gb)||typeof r=="object"&&gb(r))return!0}return!1}function IP(e){let t=0;for(let r in e){if(r==="$ref")return 1/0;if(t++,!OJ.has(r)&&(typeof e[r]=="object"&&(0,xJ.eachItem)(e[r],n=>t+=IP(n)),t===1/0))return 1/0}return t}function xP(e,t="",r){r!==!1&&(t=jc(t));let n=e.parse(t);return PP(e,n)}Xr.getFullPath=xP;function PP(e,t){return e.serialize(t).split("#")[0]+"#"}Xr._getFullPath=PP;var DJ=/#\/?$/;function jc(e){return e?e.replace(DJ,""):""}Xr.normalizeId=jc;function BJ(e,t,r){return r=jc(r),e.resolve(t,r)}Xr.resolveUrl=BJ;var WJ=/^[a-z_][-a-z0-9._]*$/i;function qJ(e,t){if(typeof e=="boolean")return{};let{schemaId:r,uriResolver:n}=this.opts,i=jc(e[r]||t),o={"":i},a=xP(n,i,!1),s={},c=new Set;return TJ(e,{allKeys:!0},(f,d,p,m)=>{if(m===void 0)return;let h=a+d,g=o[m];typeof f[r]=="string"&&(g=v.call(this,f[r])),w.call(this,f.$anchor),w.call(this,f.$dynamicAnchor),o[d]=g;function v(y){let R=this.opts.uriResolver.resolve;if(y=jc(g?R(g,y):y),c.has(y))throw u(y);c.add(y);let N=this.refs[y];return typeof N=="string"&&(N=this.refs[N]),typeof N=="object"?l(f,N.schema,y):y!==jc(h)&&(y[0]==="#"?(l(f,s[y],y),s[y]=f):this.refs[y]=h),y}function w(y){if(typeof y=="string"){if(!WJ.test(y))throw new Error(`invalid anchor "${y}"`);v.call(this,`#${y}`)}}}),s;function l(f,d,p){if(d!==void 0&&!PJ(f,d))throw u(p)}function u(f){return new Error(`reference "${f}" resolves to more than one schema`)}}Xr.getSchemaRefs=qJ});var fd=$(sa=>{"use strict";Object.defineProperty(sa,"__esModule",{value:!0});sa.getData=sa.KeywordCxt=sa.validateFunctionCode=void 0;var DP=dP(),TP=cd(),wb=cb(),zm=cd(),LJ=wP(),dd=RP(),vb=SP(),le=Ce(),me=co(),VJ=ld(),lo=Be(),ud=sd();function MJ(e){if(qP(e)&&(LP(e),WP(e))){QJ(e);return}BP(e,()=>(0,DP.topBoolOrEmptySchema)(e))}sa.validateFunctionCode=MJ;function BP({gen:e,validateName:t,schema:r,schemaEnv:n,opts:i},o){i.code.es5?e.func(t,(0,le._)`${me.default.data}, ${me.default.valCxt}`,n.$async,()=>{e.code((0,le._)`"use strict"; ${OP(r,i)}`),HJ(e,i),e.code(o)}):e.func(t,(0,le._)`${me.default.data}, ${FJ(i)}`,n.$async,()=>e.code(OP(r,i)).code(o))}function FJ(e){return(0,le._)`{${me.default.instancePath}="", ${me.default.parentData}, ${me.default.parentDataProperty}, ${me.default.rootData}=${me.default.data}${e.dynamicRef?(0,le._)`, ${me.default.dynamicAnchors}={}`:le.nil}}={}`}function HJ(e,t){e.if(me.default.valCxt,()=>{e.var(me.default.instancePath,(0,le._)`${me.default.valCxt}.${me.default.instancePath}`),e.var(me.default.parentData,(0,le._)`${me.default.valCxt}.${me.default.parentData}`),e.var(me.default.parentDataProperty,(0,le._)`${me.default.valCxt}.${me.default.parentDataProperty}`),e.var(me.default.rootData,(0,le._)`${me.default.valCxt}.${me.default.rootData}`),t.dynamicRef&&e.var(me.default.dynamicAnchors,(0,le._)`${me.default.valCxt}.${me.default.dynamicAnchors}`)},()=>{e.var(me.default.instancePath,(0,le._)`""`),e.var(me.default.parentData,(0,le._)`undefined`),e.var(me.default.parentDataProperty,(0,le._)`undefined`),e.var(me.default.rootData,me.default.data),t.dynamicRef&&e.var(me.default.dynamicAnchors,(0,le._)`{}`)})}function QJ(e){let{schema:t,opts:r,gen:n}=e;BP(e,()=>{r.$comment&&t.$comment&&MP(e),GJ(e),n.let(me.default.vErrors,null),n.let(me.default.errors,0),r.unevaluated&&UJ(e),VP(e),ZJ(e)})}function UJ(e){let{gen:t,validateName:r}=e;e.evaluated=t.const("evaluated",(0,le._)`${r}.evaluated`),t.if((0,le._)`${e.evaluated}.dynamicProps`,()=>t.assign((0,le._)`${e.evaluated}.props`,(0,le._)`undefined`)),t.if((0,le._)`${e.evaluated}.dynamicItems`,()=>t.assign((0,le._)`${e.evaluated}.items`,(0,le._)`undefined`))}function OP(e,t){let r=typeof e=="object"&&e[t.schemaId];return r&&(t.code.source||t.code.process)?(0,le._)`/*# sourceURL=${r} */`:le.nil}function JJ(e,t){if(qP(e)&&(LP(e),WP(e))){zJ(e,t);return}(0,DP.boolOrEmptySchema)(e,t)}function WP({schema:e,self:t}){if(typeof e=="boolean")return!e;for(let r in e)if(t.RULES.all[r])return!0;return!1}function qP(e){return typeof e.schema!="boolean"}function zJ(e,t){let{schema:r,gen:n,opts:i}=e;i.$comment&&r.$comment&&MP(e),YJ(e),XJ(e);let o=n.const("_errs",me.default.errors);VP(e,o),n.var(t,(0,le._)`${o} === ${me.default.errors}`)}function LP(e){(0,lo.checkUnknownRules)(e),KJ(e)}function VP(e,t){if(e.opts.jtd)return jP(e,[],!1,t);let r=(0,TP.getSchemaTypes)(e.schema),n=(0,TP.coerceAndCheckDataType)(e,r);jP(e,r,!n,t)}function KJ(e){let{schema:t,errSchemaPath:r,opts:n,self:i}=e;t.$ref&&n.ignoreKeywordsWithRef&&(0,lo.schemaHasRulesButRef)(t,i.RULES)&&i.logger.warn(`$ref: keywords ignored in schema at path "${r}"`)}function GJ(e){let{schema:t,opts:r}=e;t.default!==void 0&&r.useDefaults&&r.strictSchema&&(0,lo.checkStrictMode)(e,"default is ignored in the schema root")}function YJ(e){let t=e.schema[e.opts.schemaId];t&&(e.baseId=(0,VJ.resolveUrl)(e.opts.uriResolver,e.baseId,t))}function XJ(e){if(e.schema.$async&&!e.schemaEnv.$async)throw new Error("async schema in sync schema")}function MP({gen:e,schemaEnv:t,schema:r,errSchemaPath:n,opts:i}){let o=r.$comment;if(i.$comment===!0)e.code((0,le._)`${me.default.self}.logger.log(${o})`);else if(typeof i.$comment=="function"){let a=(0,le.str)`${n}/$comment`,s=e.scopeValue("root",{ref:t.root});e.code((0,le._)`${me.default.self}.opts.$comment(${o}, ${a}, ${s}.schema)`)}}function ZJ(e){let{gen:t,schemaEnv:r,validateName:n,ValidationError:i,opts:o}=e;r.$async?t.if((0,le._)`${me.default.errors} === 0`,()=>t.return(me.default.data),()=>t.throw((0,le._)`new ${i}(${me.default.vErrors})`)):(t.assign((0,le._)`${n}.errors`,me.default.vErrors),o.unevaluated&&e2(e),t.return((0,le._)`${me.default.errors} === 0`))}function e2({gen:e,evaluated:t,props:r,items:n}){r instanceof le.Name&&e.assign((0,le._)`${t}.props`,r),n instanceof le.Name&&e.assign((0,le._)`${t}.items`,n)}function jP(e,t,r,n){let{gen:i,schema:o,data:a,allErrors:s,opts:c,self:l}=e,{RULES:u}=l;if(o.$ref&&(c.ignoreKeywordsWithRef||!(0,lo.schemaHasRulesButRef)(o,u))){i.block(()=>HP(e,"$ref",u.all.$ref.definition));return}c.jtd||t2(e,t),i.block(()=>{for(let d of u.rules)f(d);f(u.post)});function f(d){(0,wb.shouldUseGroup)(o,d)&&(d.type?(i.if((0,zm.checkDataType)(d.type,a,c.strictNumbers)),$P(e,d),t.length===1&&t[0]===d.type&&r&&(i.else(),(0,zm.reportTypeError)(e)),i.endIf()):$P(e,d),s||i.if((0,le._)`${me.default.errors} === ${n||0}`))}}function $P(e,t){let{gen:r,schema:n,opts:{useDefaults:i}}=e;i&&(0,LJ.assignDefaults)(e,t.type),r.block(()=>{for(let o of t.rules)(0,wb.shouldUseRule)(n,o)&&HP(e,o.keyword,o.definition,t.type)})}function t2(e,t){e.schemaEnv.meta||!e.opts.strictTypes||(r2(e,t),e.opts.allowUnionTypes||n2(e,t),i2(e,e.dataTypes))}function r2(e,t){if(t.length){if(!e.dataTypes.length){e.dataTypes=t;return}t.forEach(r=>{FP(e.dataTypes,r)||yb(e,`type "${r}" not allowed by context "${e.dataTypes.join(",")}"`)}),a2(e,t)}}function n2(e,t){t.length>1&&!(t.length===2&&t.includes("null"))&&yb(e,"use allowUnionTypes to allow union type keyword")}function i2(e,t){let r=e.self.RULES.all;for(let n in r){let i=r[n];if(typeof i=="object"&&(0,wb.shouldUseRule)(e.schema,i)){let{type:o}=i.definition;o.length&&!o.some(a=>o2(t,a))&&yb(e,`missing type "${o.join(",")}" for keyword "${n}"`)}}}function o2(e,t){return e.includes(t)||t==="number"&&e.includes("integer")}function FP(e,t){return e.includes(t)||t==="integer"&&e.includes("number")}function a2(e,t){let r=[];for(let n of e.dataTypes)FP(t,n)?r.push(n):t.includes("integer")&&n==="number"&&r.push("integer");e.dataTypes=r}function yb(e,t){let r=e.schemaEnv.baseId+e.errSchemaPath;t+=` at "${r}" (strictTypes)`,(0,lo.checkStrictMode)(e,t,e.opts.strictTypes)}var Km=class{constructor(t,r,n){if((0,dd.validateKeywordUsage)(t,r,n),this.gen=t.gen,this.allErrors=t.allErrors,this.keyword=n,this.data=t.data,this.schema=t.schema[n],this.$data=r.$data&&t.opts.$data&&this.schema&&this.schema.$data,this.schemaValue=(0,lo.schemaRefOrVal)(t,this.schema,n,this.$data),this.schemaType=r.schemaType,this.parentSchema=t.schema,this.params={},this.it=t,this.def=r,this.$data)this.schemaCode=t.gen.const("vSchema",QP(this.$data,t));else if(this.schemaCode=this.schemaValue,!(0,dd.validSchemaType)(this.schema,r.schemaType,r.allowUndefined))throw new Error(`${n} value must be ${JSON.stringify(r.schemaType)}`);("code"in r?r.trackErrors:r.errors!==!1)&&(this.errsCount=t.gen.const("_errs",me.default.errors))}result(t,r,n){this.failResult((0,le.not)(t),r,n)}failResult(t,r,n){this.gen.if(t),n?n():this.error(),r?(this.gen.else(),r(),this.allErrors&&this.gen.endIf()):this.allErrors?this.gen.endIf():this.gen.else()}pass(t,r){this.failResult((0,le.not)(t),void 0,r)}fail(t){if(t===void 0){this.error(),this.allErrors||this.gen.if(!1);return}this.gen.if(t),this.error(),this.allErrors?this.gen.endIf():this.gen.else()}fail$data(t){if(!this.$data)return this.fail(t);let{schemaCode:r}=this;this.fail((0,le._)`${r} !== undefined && (${(0,le.or)(this.invalid$data(),t)})`)}error(t,r,n){if(r){this.setParams(r),this._error(t,n),this.setParams({});return}this._error(t,n)}_error(t,r){(t?ud.reportExtraError:ud.reportError)(this,this.def.error,r)}$dataError(){(0,ud.reportError)(this,this.def.$dataError||ud.keyword$DataError)}reset(){if(this.errsCount===void 0)throw new Error('add "trackErrors" to keyword definition');(0,ud.resetErrorsCount)(this.gen,this.errsCount)}ok(t){this.allErrors||this.gen.if(t)}setParams(t,r){r?Object.assign(this.params,t):this.params=t}block$data(t,r,n=le.nil){this.gen.block(()=>{this.check$data(t,n),r()})}check$data(t=le.nil,r=le.nil){if(!this.$data)return;let{gen:n,schemaCode:i,schemaType:o,def:a}=this;n.if((0,le.or)((0,le._)`${i} === undefined`,r)),t!==le.nil&&n.assign(t,!0),(o.length||a.validateSchema)&&(n.elseIf(this.invalid$data()),this.$dataError(),t!==le.nil&&n.assign(t,!1)),n.else()}invalid$data(){let{gen:t,schemaCode:r,schemaType:n,def:i,it:o}=this;return(0,le.or)(a(),s());function a(){if(n.length){if(!(r instanceof le.Name))throw new Error("ajv implementation error");let c=Array.isArray(n)?n:[n];return(0,le._)`${(0,zm.checkDataTypes)(c,r,o.opts.strictNumbers,zm.DataType.Wrong)}`}return le.nil}function s(){if(i.validateSchema){let c=t.scopeValue("validate$data",{ref:i.validateSchema});return(0,le._)`!${c}(${r})`}return le.nil}}subschema(t,r){let n=(0,vb.getSubschema)(this.it,t);(0,vb.extendSubschemaData)(n,this.it,t),(0,vb.extendSubschemaMode)(n,t);let i={...this.it,...n,items:void 0,props:void 0};return JJ(i,r),i}mergeEvaluated(t,r){let{it:n,gen:i}=this;n.opts.unevaluated&&(n.props!==!0&&t.props!==void 0&&(n.props=lo.mergeEvaluated.props(i,t.props,n.props,r)),n.items!==!0&&t.items!==void 0&&(n.items=lo.mergeEvaluated.items(i,t.items,n.items,r)))}mergeValidEvaluated(t,r){let{it:n,gen:i}=this;if(n.opts.unevaluated&&(n.props!==!0||n.items!==!0))return i.if(r,()=>this.mergeEvaluated(t,le.Name)),!0}};sa.KeywordCxt=Km;function HP(e,t,r,n){let i=new Km(e,r,t);"code"in r?r.code(i,n):i.$data&&r.validate?(0,dd.funcKeywordCode)(i,r):"macro"in r?(0,dd.macroKeywordCode)(i,r):(r.compile||r.validate)&&(0,dd.funcKeywordCode)(i,r)}var s2=/^\/(?:[^~]|~0|~1)*$/,c2=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function QP(e,{dataLevel:t,dataNames:r,dataPathArr:n}){let i,o;if(e==="")return me.default.rootData;if(e[0]==="/"){if(!s2.test(e))throw new Error(`Invalid JSON-pointer: ${e}`);i=e,o=me.default.rootData}else{let l=c2.exec(e);if(!l)throw new Error(`Invalid JSON-pointer: ${e}`);let u=+l[1];if(i=l[2],i==="#"){if(u>=t)throw new Error(c("property/index",u));return n[t-u]}if(u>t)throw new Error(c("data",u));if(o=r[t-u],!i)return o}let a=o,s=i.split("/");for(let l of s)l&&(o=(0,le._)`${o}${(0,le.getProperty)((0,lo.unescapeJsonPointer)(l))}`,a=(0,le._)`${a} && ${o}`);return a;function c(l,u){return`Cannot access ${l} ${u} levels up, current level is ${t}`}}sa.getData=QP});var Gm=$(bb=>{"use strict";Object.defineProperty(bb,"__esModule",{value:!0});var kb=class extends Error{constructor(t){super("validation failed"),this.errors=t,this.ajv=this.validation=!0}};bb.default=kb});var pd=$(Nb=>{"use strict";Object.defineProperty(Nb,"__esModule",{value:!0});var Ab=ld(),Rb=class extends Error{constructor(t,r,n,i){super(i||`can't resolve reference ${n} from id ${r}`),this.missingRef=(0,Ab.resolveUrl)(t,r,n),this.missingSchema=(0,Ab.normalizeId)((0,Ab.getFullPath)(t,this.missingRef))}};Nb.default=Rb});var Xm=$($n=>{"use strict";Object.defineProperty($n,"__esModule",{value:!0});$n.resolveSchema=$n.getCompilingSchema=$n.resolveRef=$n.compileSchema=$n.SchemaEnv=void 0;var ri=Ce(),l2=Gm(),is=co(),ni=ld(),UP=Be(),u2=fd(),$c=class{constructor(t){var r;this.refs={},this.dynamicAnchors={};let n;typeof t.schema=="object"&&(n=t.schema),this.schema=t.schema,this.schemaId=t.schemaId,this.root=t.root||this,this.baseId=(r=t.baseId)!==null&&r!==void 0?r:(0,ni.normalizeId)(n?.[t.schemaId||"$id"]),this.schemaPath=t.schemaPath,this.localRefs=t.localRefs,this.meta=t.meta,this.$async=n?.$async,this.refs={}}};$n.SchemaEnv=$c;function Eb(e){let t=JP.call(this,e);if(t)return t;let r=(0,ni.getFullPath)(this.opts.uriResolver,e.root.baseId),{es5:n,lines:i}=this.opts.code,{ownProperties:o}=this.opts,a=new ri.CodeGen(this.scope,{es5:n,lines:i,ownProperties:o}),s;e.$async&&(s=a.scopeValue("Error",{ref:l2.default,code:(0,ri._)`require("ajv/dist/runtime/validation_error").default`}));let c=a.scopeName("validate");e.validateName=c;let l={gen:a,allErrors:this.opts.allErrors,data:is.default.data,parentData:is.default.parentData,parentDataProperty:is.default.parentDataProperty,dataNames:[is.default.data],dataPathArr:[ri.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:a.scopeValue("schema",this.opts.code.source===!0?{ref:e.schema,code:(0,ri.stringify)(e.schema)}:{ref:e.schema}),validateName:c,ValidationError:s,schema:e.schema,schemaEnv:e,rootId:r,baseId:e.baseId||r,schemaPath:ri.nil,errSchemaPath:e.schemaPath||(this.opts.jtd?"":"#"),errorPath:(0,ri._)`""`,opts:this.opts,self:this},u;try{this._compilations.add(e),(0,u2.validateFunctionCode)(l),a.optimize(this.opts.code.optimize);let f=a.toString();u=`${a.scopeRefs(is.default.scope)}return ${f}`,this.opts.code.process&&(u=this.opts.code.process(u,e));let p=new Function(`${is.default.self}`,`${is.default.scope}`,u)(this,this.scope.get());if(this.scope.value(c,{ref:p}),p.errors=null,p.schema=e.schema,p.schemaEnv=e,e.$async&&(p.$async=!0),this.opts.code.source===!0&&(p.source={validateName:c,validateCode:f,scopeValues:a._values}),this.opts.unevaluated){let{props:m,items:h}=l;p.evaluated={props:m instanceof ri.Name?void 0:m,items:h instanceof ri.Name?void 0:h,dynamicProps:m instanceof ri.Name,dynamicItems:h instanceof ri.Name},p.source&&(p.source.evaluated=(0,ri.stringify)(p.evaluated))}return e.validate=p,e}catch(f){throw delete e.validate,delete e.validateName,u&&this.logger.error("Error compiling schema, function code:",u),f}finally{this._compilations.delete(e)}}$n.compileSchema=Eb;function d2(e,t,r){var n;r=(0,ni.resolveUrl)(this.opts.uriResolver,t,r);let i=e.refs[r];if(i)return i;let o=m2.call(this,e,r);if(o===void 0){let a=(n=e.localRefs)===null||n===void 0?void 0:n[r],{schemaId:s}=this.opts;a&&(o=new $c({schema:a,schemaId:s,root:e,baseId:t}))}if(o!==void 0)return e.refs[r]=f2.call(this,o)}$n.resolveRef=d2;function f2(e){return(0,ni.inlineRef)(e.schema,this.opts.inlineRefs)?e.schema:e.validate?e:Eb.call(this,e)}function JP(e){for(let t of this._compilations)if(p2(t,e))return t}$n.getCompilingSchema=JP;function p2(e,t){return e.schema===t.schema&&e.root===t.root&&e.baseId===t.baseId}function m2(e,t){let r;for(;typeof(r=this.refs[t])=="string";)t=r;return r||this.schemas[t]||Ym.call(this,e,t)}function Ym(e,t){let r=this.opts.uriResolver.parse(t),n=(0,ni._getFullPath)(this.opts.uriResolver,r),i=(0,ni.getFullPath)(this.opts.uriResolver,e.baseId,void 0);if(Object.keys(e.schema).length>0&&n===i)return Sb.call(this,r,e);let o=(0,ni.normalizeId)(n),a=this.refs[o]||this.schemas[o];if(typeof a=="string"){let s=Ym.call(this,e,a);return typeof s?.schema!="object"?void 0:Sb.call(this,r,s)}if(typeof a?.schema=="object"){if(a.validate||Eb.call(this,a),o===(0,ni.normalizeId)(t)){let{schema:s}=a,{schemaId:c}=this.opts,l=s[c];return l&&(i=(0,ni.resolveUrl)(this.opts.uriResolver,i,l)),new $c({schema:s,schemaId:c,root:e,baseId:i})}return Sb.call(this,r,a)}}$n.resolveSchema=Ym;var h2=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function Sb(e,{baseId:t,schema:r,root:n}){var i;if(((i=e.fragment)===null||i===void 0?void 0:i[0])!=="/")return;for(let s of e.fragment.slice(1).split("/")){if(typeof r=="boolean")return;let c=r[(0,UP.unescapeFragment)(s)];if(c===void 0)return;r=c;let l=typeof r=="object"&&r[this.opts.schemaId];!h2.has(s)&&l&&(t=(0,ni.resolveUrl)(this.opts.uriResolver,t,l))}let o;if(typeof r!="boolean"&&r.$ref&&!(0,UP.schemaHasRulesButRef)(r,this.RULES)){let s=(0,ni.resolveUrl)(this.opts.uriResolver,t,r.$ref);o=Ym.call(this,n,s)}let{schemaId:a}=this.opts;if(o=o||new $c({schema:r,schemaId:a,root:n,baseId:t}),o.schema!==o.root.schema)return o}});var zP=$((vne,g2)=>{g2.exports={$id:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#",description:"Meta-schema for $data reference (JSON AnySchema extension proposal)",type:"object",required:["$data"],properties:{$data:{type:"string",anyOf:[{format:"relative-json-pointer"},{format:"json-pointer"}]}},additionalProperties:!1}});var Tb=$((wne,rT)=>{"use strict";var v2=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),_b=RegExp.prototype.test.bind(/^(?:(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)$/u),w2=RegExp.prototype.test.bind(/^\d*$/u),os=RegExp.prototype.test.bind(/^[\da-f]{2}$/iu),Ib=RegExp.prototype.test.bind(/^[\da-z\-._~]$/iu),GP=RegExp.prototype.test.bind(/^[A-Za-z0-9\-._~!$&'()*+,;=:@/]$/u),xb=RegExp.prototype.test.bind(/^[A-Za-z0-9\-._~!$&'()*+,;=:@/?]$/u),y2=RegExp.prototype.test.bind(/^[A-Za-z0-9\-._~!$&'()*+,;=:]$/u),Zr=new Array(256);{let e="0123456789ABCDEF";for(let t=0;t<256;t++)Zr[t]="%"+e[t>>4]+e[t&15]}function gr(e){return e<2048?Zr[192|e>>6]+Zr[128|e&63]:e<65536?Zr[224|e>>12]+Zr[128|e>>6&63]+Zr[128|e&63]:Zr[240|e>>18]+Zr[128|e>>12&63]+Zr[128|e>>6&63]+Zr[128|e&63]}function k2(e){let t="",r=0,n=0;for(n=0;n<e.length;n++)if(r=e[n].charCodeAt(0),r!==48){if(!(r>=48&&r<=57||r>=65&&r<=70||r>=97&&r<=102))return"";t+=e[n];break}for(n+=1;n<e.length;n++){if(r=e[n].charCodeAt(0),!(r>=48&&r<=57||r>=65&&r<=70||r>=97&&r<=102))return"";t+=e[n]}return t}var b2=RegExp.prototype.test.bind(/^[\dA-Fa-f]{1,4}$/),A2=RegExp.prototype.test.bind(/^[vV][\dA-Fa-f]+\.[A-Za-z\d\-._~!$&'()*+,;=:]+$/),R2=RegExp.prototype.test.bind(/^[A-Za-z\d\-._~]$/),N2=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function S2(e){if(e.length===0)return!1;for(let t=0;t<e.length;t++)if(!R2(e[t])){if(e[t]==="%"&&t+2<e.length&&os(e.slice(t+1,t+3))){t+=2;continue}return!1}return!0}function KP(e){let t=-1,r=0,n=-1,i=0;for(let s=0;s<e.length;s++)e[s]==="0"?(n===-1&&(n=s),i++,i>r&&(r=i,t=n)):(n=-1,i=0);if(r<2)return e.join(":");let o=e.slice(0,t).join(":"),a=e.slice(t+r).join(":");return o+"::"+a}function E2(e){let t=e.indexOf("::");if(t!==-1&&e.indexOf("::",t+1)!==-1)return;let r=t===-1?e.split(":"):e.slice(0,t).split(":"),n=t===-1?[]:e.slice(t+2).split(":");t!==-1&&(r.length===1&&r[0]===""&&(r.length=0),n.length===1&&n[0]===""&&(n.length=0));let i=r.concat(n),o=0;for(let s=0;s<i.length;s++){let c=i[s];if(c==="")return;if(c.indexOf(".")!==-1){if(s!==i.length-1||t!==-1&&n.length===0||!_b(c))return;o+=2;continue}if(!b2(c))return;i[s]=parseInt(c,16).toString(16),o++}if(t===-1)return o!==8?void 0:KP(i);if(o>=8)return;let a=i.slice(0,r.length);for(let s=o;s<8;s++)a.push("0");for(let s=r.length;s<i.length;s++)a.push(i[s]);return KP(a)}function Cb(e){let t=e[0]==="["&&e[e.length-1]==="]";if((e[0]==="["||e[e.length-1]==="]")&&!t)return{host:e,isIPV6:!1,error:!0};let n=t?e.slice(1,-1):e;if(t&&A2(n))return n=n.toLowerCase(),{host:`[${n}]`,escapedHost:n,isIPV6:!1,isIPVFuture:!0};if(C2(n,":")<2)return{host:e,isIPV6:!1,error:t};let i="",o=n.indexOf("%");if(o!==-1){let s=n.slice(o,o+3).toLowerCase()==="%25"?3:1;if(i=n.slice(o+s),!S2(i))return{host:e,isIPV6:!1,error:!0};n=n.slice(0,o)}let a=E2(n);return a===void 0?{host:e,isIPV6:!1,error:!0}:{host:a+(i?"%"+i:""),escapedHost:a+(i?"%25"+i:""),isIPV6:!0}}function C2(e,t){let r=0;for(let n=0;n<e.length;n++)e[n]===t&&r++;return r}function YP(e){let t=e,r=[],n=-1,i=0;for(;i=t.length;){if(i===1){if(t===".")break;if(t==="/"){r.push("/");break}else{r.push(t);break}}else if(i===2){if(t[0]==="."){if(t[1]===".")break;if(t[1]==="/"){t=t.slice(2);continue}}else if(t[0]==="/"&&(t[1]==="."||t[1]==="/")){r.push("/");break}}else if(i===3&&t==="/.."){r.length!==0&&r.pop(),r.push("/");break}if(t[0]==="."){if(t[1]==="."){if(t[2]==="/"){t=t.slice(3);continue}}else if(t[1]==="/"){t=t.slice(2);continue}}else if(t[0]==="/"&&t[1]==="."){if(t[2]==="/"){t=t.slice(2);continue}else if(t[2]==="."&&t[3]==="/"){t=t.slice(3),r.length!==0&&r.pop();continue}}if((n=t.indexOf("/",1))===-1){r.push(t);break}else r.push(t.slice(0,n)),t=t.slice(n)}return r.join("")}function _2(e){if(e===""||e[0]==="/")return YP(e);let t=e.split("/"),r=t.length-1,n=[],i=!1;for(let o=0;o<=r;o++){let a=t[o];a==="."||a===".."?(a===".."&&(n.length!==0&&n[n.length-1]!==".."?n.pop():n.push("..")),i=o===r):n.push(a)}return i&&n[n.length-1]!==".."&&n.push(""),(n.length===0||n[0]===""||n[0].includes(":"))&&n.unshift("."),n.join("/")}var I2={"@":"%40","/":"%2F","?":"%3F","#":"%23",":":"%3A"},x2=/[@/?#:]/g,P2=/[@/?#]/g;function XP(e,t){let r=t?P2:x2;return r.lastIndex=0,e.replace(r,n=>I2[n])}function ZP(e,t=!1){if(e.indexOf("%")===-1)return e;let r="";for(let n=0;n<e.length;n++){if(e[n]==="%"&&n+2<e.length){let i=e.slice(n+1,n+3);if(os(i)){let o=i.toUpperCase(),a=String.fromCharCode(parseInt(o,16));t&&Ib(a)?r+=a:r+="%"+o,n+=2;continue}}r+=e[n]}return r}function T2(e){let t="";for(let r=0;r<e.length;r++){let n=e[r];if(n==="%"&&r+2<e.length){let i=e.slice(r+1,r+3);if(os(i)){let o=i.toUpperCase(),a=String.fromCharCode(parseInt(o,16));a!=="."&&Ib(a)?t+=a:t+="%"+o,r+=2;continue}}if(GP(n))t+=n;else{let i=e.charCodeAt(r);if(i<128)t+=tT(i)?n:Zr[i];else if(i<55296||i>57343)t+=gr(i);else if(i<=56319&&r+1<e.length){let o=e.charCodeAt(r+1);o>=56320&&o<=57343?(t+=gr(65536+(i-55296<<10)+(o-56320)),r++):t+=gr(65533)}else t+=gr(65533)}}return t}function O2(e,t=!1){let r="",n=t&&e[0]!=="/";for(let i=0;i<e.length;i++){let o=e[i];if(o==="%"&&i+2<e.length){let a=e.slice(i+1,i+3);if(os(a)){r+="%"+a.toUpperCase(),i+=2;continue}}if(o==="/"&&(n=!1),GP(o)&&(o!==":"||!n))r+=o;else{let a=e.charCodeAt(i);if(a<128)r+=Zr[a];else if(a<55296||a>57343)r+=gr(a);else if(a<=56319&&i+1<e.length){let s=e.charCodeAt(i+1);s>=56320&&s<=57343?(r+=gr(65536+(a-55296<<10)+(s-56320)),i++):r+=gr(65533)}else r+=gr(65533)}}return r}function Pb(e,t){let r="";for(let n=0;n<e.length;n++){let i=e[n];if(i==="%"&&n+2<e.length){let o=e.slice(n+1,n+3);if(os(o)){r+="%"+o.toUpperCase(),n+=2;continue}}if(t(i))r+=i;else{let o=e.charCodeAt(n);if(o<128)r+=Zr[o];else if(o<55296||o>57343)r+=gr(o);else if(o<=56319&&n+1<e.length){let a=e.charCodeAt(n+1);a>=56320&&a<=57343?(r+=gr(65536+(o-55296<<10)+(a-56320)),n++):r+=gr(65533)}else r+=gr(65533)}}return r}function eT(e){return Pb(e,y2)}function j2(e){return Pb(e,xb)}function $2(e){return Pb(e,xb)}function tT(e){return e>=48&&e<=57||e>=65&&e<=90||e>=97&&e<=122||e===42||e===43||e===45||e===46||e===47||e===64||e===95}function D2(e){let t="";for(let r=0;r<e.length;r++){let n=e[r];if(n==="%"&&r+2<e.length){let i=e.slice(r+1,r+3);if(os(i)){let o=i.toUpperCase(),a=String.fromCharCode(parseInt(o,16));Ib(a)?t+=a:t+="%"+o,r+=2;continue}}if(xb(n))t+=n;else{let i=e.charCodeAt(r);if(i<128)t+=tT(i)?n:Zr[i];else if(i<55296||i>57343)t+=gr(i);else if(i<=56319&&r+1<e.length){let o=e.charCodeAt(r+1);o>=56320&&o<=57343?(t+=gr(65536+(i-55296<<10)+(o-56320)),r++):t+=gr(65533)}else t+=gr(65533)}}return t}function B2(e){let t="";for(let r=0;r<e.length;r++){if(e[r]==="%"&&r+2<e.length){let n=e.slice(r+1,r+3);if(os(n)){t+="%"+n.toUpperCase(),r+=2;continue}}t+=escape(e[r])}return t}function W2(e){let t=[];if(e.userinfo!==void 0&&(t.push(eT(e.userinfo)),t.push("@")),e.host!==void 0){let r=e.host;if(!_b(r)){let n=Cb(r);n.isIPV6!==!0&&n.isIPVFuture!==!0&&(r=ZP(r,!0),n=Cb(r)),n.isIPV6===!0||n.isIPVFuture===!0?r=`[${n.escapedHost}]`:r=XP(r,!1)}t.push(r)}if(typeof e.port=="number"||typeof e.port=="string"){let r=String(e.port);if(!w2(r))throw new TypeError("URI port is malformed.");t.push(":"),t.push(r)}return t.length?t.join(""):void 0}rT.exports={nonSimpleDomain:N2,recomposeAuthority:W2,reescapeHostDelimiters:XP,normalizePercentEncoding:ZP,normalizePathEncoding:T2,serializePathEncoding:O2,normalizeQueryFragmentEncoding:D2,encodeUserinfo:eT,encodeQuery:j2,encodeFragment:$2,escapePreservingEscapes:B2,removeDotSegments:YP,removeDotSegmentsRelative:_2,isIPv4:_b,isUUID:v2,normalizeIPv6:Cb,stringArrayToHexStripped:k2}});var sT=$((yne,aT)=>{"use strict";var{isUUID:q2}=Tb(),L2=/^([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-./:;=@]|%[\da-f]{2})+)$/iu,V2=["http","https","ws","wss","urn","urn:uuid"];function M2(e){return V2.indexOf(e)!==-1}function Ob(e){return e.secure===!0?!0:e.secure===!1?!1:e.scheme?e.scheme.length===3&&(e.scheme[0]==="w"||e.scheme[0]==="W")&&(e.scheme[1]==="s"||e.scheme[1]==="S")&&(e.scheme[2]==="s"||e.scheme[2]==="S"):!1}function nT(e){return e.host||(e.error=e.error||"HTTP URIs must have a host."),e}function iT(e){let t=String(e.scheme).toLowerCase()==="https";return(e.port===(t?443:80)||e.port==="")&&(e.port=void 0),e.path||(e.path="/"),e}function F2(e){return e.secure=Ob(e),e.resourceName=(e.path||"/")+(e.query?"?"+e.query:""),e.path=void 0,e.query=void 0,e}function H2(e){if((e.port===(Ob(e)?443:80)||e.port==="")&&(e.port=void 0),typeof e.secure=="boolean"&&(e.scheme=e.secure?"wss":"ws",e.secure=void 0),e.resourceName){let t=e.resourceName.indexOf("?"),r=t===-1?e.resourceName:e.resourceName.slice(0,t);e.path=r&&r!=="/"?r:void 0,e.query=t===-1?void 0:e.resourceName.slice(t+1),e.resourceName=void 0}return e.fragment=void 0,e}function Q2(e,t){if(!e.path)return e.error="URN can not be parsed",e;let r=e.path.match(L2);if(r&&r[0]===e.path){let n=t.scheme||e.scheme||"urn";e.nid=r[1].toLowerCase(),e.nss=r[2];let i=`${n}:${t.nid||e.nid}`,o=jb(i);e.path=void 0,o&&(e=o.parse(e,t))}else e.error=e.error||"URN can not be parsed.";return e}function U2(e,t){if(e.nid===void 0)throw new Error("URN without nid cannot be serialized");let r=t.scheme||e.scheme||"urn",n=e.nid.toLowerCase(),i=`${r}:${t.nid||n}`,o=jb(i);o&&(e=o.serialize(e,t));let a=e,s=e.nss;return a.path=`${n||t.nid}:${s}`,t.skipEscape=!0,a}function J2(e,t){let r=e;return r.uuid=r.nss,r.nss=void 0,!t.tolerant&&(!r.uuid||!q2(r.uuid))&&(r.error=r.error||"UUID is not valid."),r}function z2(e){let t=e;return t.nss=(e.uuid||"").toLowerCase(),t}var oT={scheme:"http",domainHost:!0,parse:nT,serialize:iT},K2={scheme:"https",domainHost:oT.domainHost,parse:nT,serialize:iT},Zm={scheme:"ws",domainHost:!0,parse:F2,serialize:H2},G2={scheme:"wss",domainHost:Zm.domainHost,parse:Zm.parse,serialize:Zm.serialize},Y2={scheme:"urn",parse:Q2,serialize:U2,skipNormalize:!0},X2={scheme:"urn:uuid",parse:J2,serialize:z2,skipNormalize:!0},eh={http:oT,https:K2,ws:Zm,wss:G2,urn:Y2,"urn:uuid":X2};Object.setPrototypeOf(eh,null);function jb(e){return e&&(eh[e]||eh[e.toLowerCase()])||void 0}aT.exports={wsIsSecure:Ob,SCHEMES:eh,isValidSchemeName:M2,getSchemeHandler:jb}});var AT=$((kne,oh)=>{"use strict";var{normalizeIPv6:fT,removeDotSegments:hd,removeDotSegmentsRelative:pT,recomposeAuthority:Z2,normalizePercentEncoding:$b,normalizePathEncoding:ez,serializePathEncoding:cT,normalizeQueryFragmentEncoding:lT,encodeQuery:tz,encodeFragment:rz,reescapeHostDelimiters:nz,isIPv4:mT,nonSimpleDomain:iz}=Tb(),{SCHEMES:hT,getSchemeHandler:Db}=sT(),gT=/^[A-Za-z][A-Za-z0-9+.-]*$/u,vT="URI scheme is malformed.",th="URI host is malformed.",oz=/[\0-\x20"#/:<>?@[\\\]^`{|}\x7F]/u;function uT(e){let t=String(e);if(!gT.test(t))throw new TypeError(vT);return t}function az(e,t){return typeof e=="string"?e=hz(e,t):typeof e=="object"&&(e=nh(as(e,t),t)),e}function sz(e,t,r){let n=r?Object.assign({scheme:"null"},r):{scheme:"null"},{parsed:i,malformedAuthorityOrPort:o,malformedPercentEncoding:a,malformedSchemeSpecific:s,malformedHost:c,malformedScheme:l}=rh(e,n),{parsed:u,malformedAuthorityOrPort:f,malformedPercentEncoding:d,malformedSchemeSpecific:p,malformedHost:m,malformedScheme:h}=rh(t,n);if(o||f||a||d||s||p||c||m||l||h)throw new Error(i.error||u.error||"URI is malformed.");let g=wT(i,u,n,!0),v=Db(r&&r.scheme||g.scheme),w=g.host,y=w!==void 0&&w!==""&&(mT(w)||fT(w).isIPV6);if(kT(g,r||{},v,y))throw new Error(th);yT(g,r||{},v,y);let R=w&&w.indexOf("%")!==-1&&!new RegExp("\\P{ASCII}","u").test(w);if(g.error&&!R)throw new Error(g.error);return n.skipEscape=!0,as(g,n)}function wT(e,t,r,n){let i={};if(n||(e=nh(as(e,r),r),t=nh(as(t,r),r)),r=r||{},!r.tolerant&&t.scheme)i.scheme=t.scheme,i.userinfo=t.userinfo,i.host=t.host,i.port=t.port,i.path=hd(t.path||""),i.query=t.query;else{if(t.userinfo!==void 0||t.host!==void 0||t.port!==void 0)i.userinfo=t.userinfo,i.host=t.host,i.port=t.port,i.path=hd(t.path||""),i.query=t.query;else{if(!t.path)i.path=e.path,t.query!==void 0?i.query=t.query:i.query=e.query;else{if(t.path[0]==="/")i.path=hd(t.path);else{let o=e.userinfo!==void 0||e.host!==void 0||e.port!==void 0;o&&!e.path?i.path="/"+t.path:e.path?i.path=e.path.slice(0,e.path.lastIndexOf("/")+1)+t.path:i.path=t.path,i.path=e.scheme===void 0&&!o&&i.path[0]!=="/"?pT(i.path):hd(i.path)}i.query=t.query}i.userinfo=e.userinfo,i.host=e.host,i.port=e.port}i.scheme=e.scheme}return i.fragment=t.fragment,i}function cz(e,t,r){let n=dT(e,r),i=dT(t,r);return n!==void 0&&i!==void 0&&n===i}function as(e,t){let r={host:e.host,scheme:e.scheme,userinfo:e.userinfo,port:e.port,path:e.path,query:e.query,nid:e.nid,nss:e.nss,uuid:e.uuid,fragment:e.fragment,reference:e.reference,resourceName:e.resourceName,secure:e.secure,error:""},n=Object.assign({},t),i=[];r.scheme&&(r.scheme=uT(r.scheme));let o=Db(n.scheme||r.scheme);o&&o.serialize&&o.serialize(r,n);let a=r.userinfo!==void 0||r.host!==void 0||r.port!==void 0,s=(r.scheme===void 0||n.reference==="suffix")&&!a,c=!n.skipEscape&&s;r.path!==void 0&&(n.skipEscape?r.path=$b(r.path):r.path=cT(r.path,c)),n.reference!=="suffix"&&r.scheme&&(r.scheme=uT(r.scheme),i.push(r.scheme,":"));let l=Z2(r);if(l!==void 0&&(n.reference!=="suffix"&&i.push("//"),i.push(l),r.path&&r.path[0]!=="/"&&i.push("/")),r.path!==void 0){let u=r.path;!n.absolutePath&&(!o||!o.absolutePath)&&(u=s&&u[0]!=="/"?pT(u):hd(u)),s&&(u=cT(u,!0)),l===void 0&&u[0]==="/"&&u[1]==="/"&&(u="/%2F"+u.slice(2)),i.push(u)}return r.query!==void 0&&i.push("?",tz(r.query)),r.fragment!==void 0&&i.push("#",rz(r.fragment)),i.join("")}var lz=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u,uz=/^(?:[^#/:?]+:)?\/\/([^/?#]*)/,dz=/^(?:[^#/:?]+:)?([/\\\t\n\r]*)/;function fz(e,t){if(t[2]!==void 0&&e.path&&e.path[0]!=="/")return'URI path must start with "/" when authority is present.';if(typeof e.port=="number"&&(e.port<0||e.port>65535))return"URI port is malformed."}function md(e){if(e===void 0)return!1;let t=e.indexOf("%");for(;t!==-1;){if(t+2>=e.length||!/^[\da-f]{2}$/iu.test(e.slice(t+1,t+3)))return!0;t=e.indexOf("%",t+3)}return!1}function ih(e){return e[0]==="["&&e[e.length-1]==="]"}function pz(e){let t=e[4];return md(e[3])||t!==void 0&&!ih(t)&&md(t)||md(e[6])||md(e[7])||md(e[8])}function yT(e,t,r,n){if(kT(e,t,r,n))return e.error=e.error||th,!0;if(!t.unicodeSupport&&(!r||!r.unicodeSupport)&&e.host&&!ih(e.host)&&(t.domainHost||r&&r.domainHost)&&n===!1&&iz(e.host)){let i;try{i=new URL("http://"+e.host)}catch(o){return e.error=e.error||"Host's domain name can not be converted to ASCII: "+o,!0}if(!mz(i))return e.error=e.error||th,!0;e.host=i.hostname}return!1}function kT(e,t,r,n){return!!(e.host&&n===!1&&!ih(e.host)&&(t.domainHost||r&&r.domainHost)&&oz.test(e.host))}function mz(e){return e.username===""&&e.password===""&&e.port===""&&e.pathname==="/"&&e.search===""&&e.hash===""&&e.hostname!==""}function rh(e,t){let r=Object.assign({},t),n={scheme:void 0,userinfo:void 0,host:"",port:void 0,path:"",query:void 0,fragment:void 0},i=!1,o=!1,a=!1,s=!1,c=!1,l=!1,u=!1;r.reference==="suffix"&&(r.scheme?e=r.scheme+":"+e:e="//"+e);let f=e.match(uz);f!==null&&f[1].indexOf("\\")!==-1&&(n.error="URI authority must not contain a literal backslash.",i=!0);let d=e.match(dz);if(d!==null){let m=d[1],h=m.replace(/[\t\n\r]/g,"");h.length>=2&&(h.slice(0,2)!=="//"?(n.error=n.error||"URI authority must not contain a literal backslash.",i=!0):m.length!==h.length&&(n.error=n.error||"URI authority introducer must not contain whitespace.",i=!0))}let p=e.match(lz);if(p){n.scheme=p[1],n.userinfo=p[3],n.host=p[4],n.port=parseInt(p[5],10),n.path=p[6]||"",n.query=p[7],n.fragment=p[8],n.scheme!==void 0&&(gT.test(n.scheme)?n.scheme=n.scheme.toLowerCase():(n.error=n.error||vT,l=!0)),o=pz(p),o&&(n.error=n.error||"URI contains malformed percent-encoding."),isNaN(n.port)&&(n.port=p[5]);let m=fz(n,p);if(m!==void 0&&(n.error=n.error||m,i=!0),n.host)if(mT(n.host)===!1){let v=ih(n.host),w=n.host.indexOf("[")!==-1||n.host.indexOf("]")!==-1,y=fT(n.host);u=y.isIPV6||y.isIPVFuture===!0,c=w&&(!v||y.error===!0),n.host=u?y.host:y.host.toLowerCase(),c&&(n.error=n.error||th,i=!0)}else u=!0;n.scheme===void 0&&n.userinfo===void 0&&n.host===void 0&&n.port===void 0&&n.query===void 0&&!n.path?n.reference="same-document":n.scheme===void 0?n.reference="relative":n.fragment===void 0?n.reference="absolute":n.reference="uri",r.reference&&r.reference!=="suffix"&&r.reference!==n.reference&&(n.error=n.error||"URI is not a "+r.reference+" reference.");let h=Db(r.scheme||n.scheme);if(c||(s=yT(n,r,h,u)),e.indexOf("%")!==-1&&n.host!==void 0&&!c){let g=u?n.host:$b(n.host,!0);u||(g=$b(g.toLowerCase())),n.host=u||r.scheme!=="null"?nz(g,u):g}(!h||h&&!h.skipNormalize)&&(n.path&&(n.path=ez(n.path)),n.query&&(n.query=lT(n.query)),n.fragment&&(n.fragment=lT(n.fragment))),h&&h.parse&&(h.parse(n,r),h===hT.urn&&n.nid===void 0&&(a=!0))}else n.error=n.error||"URI can not be parsed.";return{parsed:n,malformedAuthorityOrPort:i,malformedPercentEncoding:o,malformedSchemeSpecific:a,malformedHost:s,malformedScheme:l}}function nh(e,t){return rh(e,t).parsed}function hz(e,t){return bT(e,t).normalized}function bT(e,t){let{parsed:r,malformedAuthorityOrPort:n,malformedPercentEncoding:i,malformedSchemeSpecific:o,malformedHost:a,malformedScheme:s}=rh(e,t);return{normalized:n||i||o||a||s?e:as(r,t),malformedAuthorityOrPort:n,malformedPercentEncoding:i,malformedSchemeSpecific:o,malformedHost:a,malformedScheme:s}}function dT(e,t){if(typeof e!="string"&&typeof e!="object")return;let r;try{r=typeof e=="string"?e:as(e,t)}catch{return}let{normalized:n,malformedAuthorityOrPort:i,malformedPercentEncoding:o,malformedSchemeSpecific:a,malformedHost:s,malformedScheme:c}=bT(r,t);return i||o||a||s||c?void 0:n}var Bb={SCHEMES:hT,normalize:az,resolve:sz,resolveComponent:wT,equal:cz,serialize:as,parse:nh};oh.exports=Bb;oh.exports.default=Bb;oh.exports.fastUri=Bb});var NT=$(Wb=>{"use strict";Object.defineProperty(Wb,"__esModule",{value:!0});var RT=AT();RT.code='require("ajv/dist/runtime/uri").default';Wb.default=RT});var TT=$(ar=>{"use strict";Object.defineProperty(ar,"__esModule",{value:!0});ar.CodeGen=ar.Name=ar.nil=ar.stringify=ar.str=ar._=ar.KeywordCxt=void 0;var gz=fd();Object.defineProperty(ar,"KeywordCxt",{enumerable:!0,get:function(){return gz.KeywordCxt}});var Dc=Ce();Object.defineProperty(ar,"_",{enumerable:!0,get:function(){return Dc._}});Object.defineProperty(ar,"str",{enumerable:!0,get:function(){return Dc.str}});Object.defineProperty(ar,"stringify",{enumerable:!0,get:function(){return Dc.stringify}});Object.defineProperty(ar,"nil",{enumerable:!0,get:function(){return Dc.nil}});Object.defineProperty(ar,"Name",{enumerable:!0,get:function(){return Dc.Name}});Object.defineProperty(ar,"CodeGen",{enumerable:!0,get:function(){return Dc.CodeGen}});var vz=Gm(),IT=pd(),wz=sb(),gd=Xm(),yz=Ce(),vd=ld(),ah=cd(),Lb=Be(),ST=zP(),kz=NT(),xT=(e,t)=>new RegExp(e,t);xT.code="new RegExp";var bz=["removeAdditional","useDefaults","coerceTypes"],Az=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),Rz={errorDataPath:"",format:"`validateFormats: false` can be used instead.",nullable:'"nullable" keyword is supported by default.',jsonPointers:"Deprecated jsPropertySyntax can be used instead.",extendRefs:"Deprecated ignoreKeywordsWithRef can be used instead.",missingRefs:"Pass empty schema with $id that should be ignored to ajv.addSchema.",processCode:"Use option `code: {process: (code, schemaEnv: object) => string}`",sourceCode:"Use option `code: {source: true}`",strictDefaults:"It is default now, see option `strict`.",strictKeywords:"It is default now, see option `strict`.",uniqueItems:'"uniqueItems" keyword is always validated.',unknownFormats:"Disable strict mode or pass `true` to `ajv.addFormat` (or `formats` option).",cache:"Map is used as cache, schema object as key.",serialize:"Map is used as cache, schema object as key.",ajvErrors:"It is default now."},Nz={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'},ET=200;function Sz(e){var t,r,n,i,o,a,s,c,l,u,f,d,p,m,h,g,v,w,y,R,N,b,E,I,W;let F=e.strict,G=(t=e.code)===null||t===void 0?void 0:t.optimize,Z=G===!0||G===void 0?1:G||0,Ae=(n=(r=e.code)===null||r===void 0?void 0:r.regExp)!==null&&n!==void 0?n:xT,re=(i=e.uriResolver)!==null&&i!==void 0?i:kz.default;return{strictSchema:(a=(o=e.strictSchema)!==null&&o!==void 0?o:F)!==null&&a!==void 0?a:!0,strictNumbers:(c=(s=e.strictNumbers)!==null&&s!==void 0?s:F)!==null&&c!==void 0?c:!0,strictTypes:(u=(l=e.strictTypes)!==null&&l!==void 0?l:F)!==null&&u!==void 0?u:"log",strictTuples:(d=(f=e.strictTuples)!==null&&f!==void 0?f:F)!==null&&d!==void 0?d:"log",strictRequired:(m=(p=e.strictRequired)!==null&&p!==void 0?p:F)!==null&&m!==void 0?m:!1,code:e.code?{...e.code,optimize:Z,regExp:Ae}:{optimize:Z,regExp:Ae},loopRequired:(h=e.loopRequired)!==null&&h!==void 0?h:ET,loopEnum:(g=e.loopEnum)!==null&&g!==void 0?g:ET,meta:(v=e.meta)!==null&&v!==void 0?v:!0,messages:(w=e.messages)!==null&&w!==void 0?w:!0,inlineRefs:(y=e.inlineRefs)!==null&&y!==void 0?y:!0,schemaId:(R=e.schemaId)!==null&&R!==void 0?R:"$id",addUsedSchema:(N=e.addUsedSchema)!==null&&N!==void 0?N:!0,validateSchema:(b=e.validateSchema)!==null&&b!==void 0?b:!0,validateFormats:(E=e.validateFormats)!==null&&E!==void 0?E:!0,unicodeRegExp:(I=e.unicodeRegExp)!==null&&I!==void 0?I:!0,int32range:(W=e.int32range)!==null&&W!==void 0?W:!0,uriResolver:re}}var wd=class{constructor(t={}){this.schemas={},this.refs={},this.formats=Object.create(null),this._compilations=new Set,this._loading={},this._cache=new Map,t=this.opts={...t,...Sz(t)};let{es5:r,lines:n}=this.opts.code;this.scope=new yz.ValueScope({scope:{},prefixes:Az,es5:r,lines:n}),this.logger=Pz(t.logger);let i=t.validateFormats;t.validateFormats=!1,this.RULES=(0,wz.getRules)(),CT.call(this,Rz,t,"NOT SUPPORTED"),CT.call(this,Nz,t,"DEPRECATED","warn"),this._metaOpts=Iz.call(this),t.formats&&Cz.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),t.keywords&&_z.call(this,t.keywords),typeof t.meta=="object"&&this.addMetaSchema(t.meta),Ez.call(this),t.validateFormats=i}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){let{$data:t,meta:r,schemaId:n}=this.opts,i=ST;n==="id"&&(i={...ST},i.id=i.$id,delete i.$id),r&&t&&this.addMetaSchema(i,i[n],!1)}defaultMeta(){let{meta:t,schemaId:r}=this.opts;return this.opts.defaultMeta=typeof t=="object"?t[r]||t:void 0}validate(t,r){let n;if(typeof t=="string"){if(n=this.getSchema(t),!n)throw new Error(`no schema with key or ref "${t}"`)}else n=this.compile(t);let i=n(r);return"$async"in n||(this.errors=n.errors),i}compile(t,r){let n=this._addSchema(t,r);return n.validate||this._compileSchemaEnv(n)}compileAsync(t,r){if(typeof this.opts.loadSchema!="function")throw new Error("options.loadSchema should be a function");let{loadSchema:n}=this.opts;return i.call(this,t,r);async function i(u,f){await o.call(this,u.$schema);let d=this._addSchema(u,f);return d.validate||a.call(this,d)}async function o(u){u&&!this.getSchema(u)&&await i.call(this,{$ref:u},!0)}async function a(u){try{return this._compileSchemaEnv(u)}catch(f){if(!(f instanceof IT.default))throw f;return s.call(this,f),await c.call(this,f.missingSchema),a.call(this,u)}}function s({missingSchema:u,missingRef:f}){if(this.refs[u])throw new Error(`AnySchema ${u} is loaded but ${f} cannot be resolved`)}async function c(u){let f=await l.call(this,u);this.refs[u]||await o.call(this,f.$schema),this.refs[u]||this.addSchema(f,u,r)}async function l(u){let f=this._loading[u];if(f)return f;try{return await(this._loading[u]=n(u))}finally{delete this._loading[u]}}}addSchema(t,r,n,i=this.opts.validateSchema){if(Array.isArray(t)){for(let a of t)this.addSchema(a,void 0,n,i);return this}let o;if(typeof t=="object"){let{schemaId:a}=this.opts;if(o=t[a],o!==void 0&&typeof o!="string")throw new Error(`schema ${a} must be string`)}return r=(0,vd.normalizeId)(r||o),this._checkUnique(r),this.schemas[r]=this._addSchema(t,n,r,i,!0),this}addMetaSchema(t,r,n=this.opts.validateSchema){return this.addSchema(t,r,!0,n),this}validateSchema(t,r){if(typeof t=="boolean")return!0;let n;if(n=t.$schema,n!==void 0&&typeof n!="string")throw new Error("$schema must be a string");if(n=n||this.opts.defaultMeta||this.defaultMeta(),!n)return this.logger.warn("meta-schema not available"),this.errors=null,!0;let i=this.validate(n,t);if(!i&&r){let o="schema is invalid: "+this.errorsText();if(this.opts.validateSchema==="log")this.logger.error(o);else throw new Error(o)}return i}getSchema(t){let r;for(;typeof(r=_T.call(this,t))=="string";)t=r;if(r===void 0){let{schemaId:n}=this.opts,i=new gd.SchemaEnv({schema:{},schemaId:n});if(r=gd.resolveSchema.call(this,i,t),!r)return;this.refs[t]=r}return r.validate||this._compileSchemaEnv(r)}removeSchema(t){if(t instanceof RegExp)return this._removeAllSchemas(this.schemas,t),this._removeAllSchemas(this.refs,t),this;switch(typeof t){case"undefined":return this._removeAllSchemas(this.schemas),this._removeAllSchemas(this.refs),this._cache.clear(),this;case"string":{let r=_T.call(this,t);return typeof r=="object"&&this._cache.delete(r.schema),delete this.schemas[t],delete this.refs[t],this}case"object":{let r=t;this._cache.delete(r);let n=t[this.opts.schemaId];return n&&(n=(0,vd.normalizeId)(n),delete this.schemas[n],delete this.refs[n]),this}default:throw new Error("ajv.removeSchema: invalid parameter")}}addVocabulary(t){for(let r of t)this.addKeyword(r);return this}addKeyword(t,r){let n;if(typeof t=="string")n=t,typeof r=="object"&&(this.logger.warn("these parameters are deprecated, see docs for addKeyword"),r.keyword=n);else if(typeof t=="object"&&r===void 0){if(r=t,n=r.keyword,Array.isArray(n)&&!n.length)throw new Error("addKeywords: keyword must be string or non-empty array")}else throw new Error("invalid addKeywords parameters");if(Oz.call(this,n,r),!r)return(0,Lb.eachItem)(n,o=>qb.call(this,o)),this;$z.call(this,r);let i={...r,type:(0,ah.getJSONTypes)(r.type),schemaType:(0,ah.getJSONTypes)(r.schemaType)};return(0,Lb.eachItem)(n,i.type.length===0?o=>qb.call(this,o,i):o=>i.type.forEach(a=>qb.call(this,o,i,a))),this}getKeyword(t){let r=this.RULES.all[t];return typeof r=="object"?r.definition:!!r}removeKeyword(t){let{RULES:r}=this;delete r.keywords[t],delete r.all[t];for(let n of r.rules){let i=n.rules.findIndex(o=>o.keyword===t);i>=0&&n.rules.splice(i,1)}return this}addFormat(t,r){return typeof r=="string"&&(r=new RegExp(r)),this.formats[t]=r,this}errorsText(t=this.errors,{separator:r=", ",dataVar:n="data"}={}){return!t||t.length===0?"No errors":t.map(i=>`${n}${i.instancePath} ${i.message}`).reduce((i,o)=>i+r+o)}$dataMetaSchema(t,r){let n=this.RULES.all;t=JSON.parse(JSON.stringify(t));for(let i of r){let o=i.split("/").slice(1),a=t;for(let s of o)a=a[s];for(let s in n){let c=n[s];if(typeof c!="object")continue;let{$data:l}=c.definition,u=a[s];l&&u&&(a[s]=PT(u))}}return t}_removeAllSchemas(t,r){for(let n in t){let i=t[n];(!r||r.test(n))&&(typeof i=="string"?delete t[n]:i&&!i.meta&&(this._cache.delete(i.schema),delete t[n]))}}_addSchema(t,r,n,i=this.opts.validateSchema,o=this.opts.addUsedSchema){let a,{schemaId:s}=this.opts;if(typeof t=="object")a=t[s];else{if(this.opts.jtd)throw new Error("schema must be object");if(typeof t!="boolean")throw new Error("schema must be object or boolean")}let c=this._cache.get(t);if(c!==void 0)return c;n=(0,vd.normalizeId)(a||n);let l=vd.getSchemaRefs.call(this,t,n);return c=new gd.SchemaEnv({schema:t,schemaId:s,meta:r,baseId:n,localRefs:l}),this._cache.set(c.schema,c),o&&!n.startsWith("#")&&(n&&this._checkUnique(n),this.refs[n]=c),i&&this.validateSchema(t,!0),c}_checkUnique(t){if(this.schemas[t]||this.refs[t])throw new Error(`schema with key or id "${t}" already exists`)}_compileSchemaEnv(t){if(t.meta?this._compileMetaSchema(t):gd.compileSchema.call(this,t),!t.validate)throw new Error("ajv implementation error");return t.validate}_compileMetaSchema(t){let r=this.opts;this.opts=this._metaOpts;try{gd.compileSchema.call(this,t)}finally{this.opts=r}}};wd.ValidationError=vz.default;wd.MissingRefError=IT.default;ar.default=wd;function CT(e,t,r,n="error"){for(let i in e){let o=i;o in t&&this.logger[n](`${r}: option ${i}. ${e[o]}`)}}function _T(e){return e=(0,vd.normalizeId)(e),this.schemas[e]||this.refs[e]}function Ez(){let e=this.opts.schemas;if(e)if(Array.isArray(e))this.addSchema(e);else for(let t in e)this.addSchema(e[t],t)}function Cz(){for(let e in this.opts.formats){let t=this.opts.formats[e];t&&this.addFormat(e,t)}}function _z(e){if(Array.isArray(e)){this.addVocabulary(e);return}this.logger.warn("keywords option as map is deprecated, pass array");for(let t in e){let r=e[t];r.keyword||(r.keyword=t),this.addKeyword(r)}}function Iz(){let e={...this.opts};for(let t of bz)delete e[t];return e}var xz={log(){},warn(){},error(){}};function Pz(e){if(e===!1)return xz;if(e===void 0)return console;if(e.log&&e.warn&&e.error)return e;throw new Error("logger must implement log, warn and error methods")}var Tz=/^[a-z_$][a-z0-9_$:-]*$/i;function Oz(e,t){let{RULES:r}=this;if((0,Lb.eachItem)(e,n=>{if(r.keywords[n])throw new Error(`Keyword ${n} is already defined`);if(!Tz.test(n))throw new Error(`Keyword ${n} has invalid name`)}),!!t&&t.$data&&!("code"in t||"validate"in t))throw new Error('$data keyword must have "code" or "validate" function')}function qb(e,t,r){var n;let i=t?.post;if(r&&i)throw new Error('keyword with "post" flag cannot have "type"');let{RULES:o}=this,a=i?o.post:o.rules.find(({type:c})=>c===r);if(a||(a={type:r,rules:[]},o.rules.push(a)),o.keywords[e]=!0,!t)return;let s={keyword:e,definition:{...t,type:(0,ah.getJSONTypes)(t.type),schemaType:(0,ah.getJSONTypes)(t.schemaType)}};t.before?jz.call(this,a,s,t.before):a.rules.push(s),o.all[e]=s,(n=t.implements)===null||n===void 0||n.forEach(c=>this.addKeyword(c))}function jz(e,t,r){let n=e.rules.findIndex(i=>i.keyword===r);n>=0?e.rules.splice(n,0,t):(e.rules.push(t),this.logger.warn(`rule ${r} is not defined`))}function $z(e){let{metaSchema:t}=e;t!==void 0&&(e.$data&&this.opts.$data&&(t=PT(t)),e.validateSchema=this.compile(t,!0))}var Dz={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function PT(e){return{anyOf:[e,Dz]}}});var OT=$(Vb=>{"use strict";Object.defineProperty(Vb,"__esModule",{value:!0});var Bz={keyword:"id",code(){throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};Vb.default=Bz});var BT=$(ss=>{"use strict";Object.defineProperty(ss,"__esModule",{value:!0});ss.callRef=ss.getValidate=void 0;var Wz=pd(),jT=jn(),en=Ce(),Bc=co(),$T=Xm(),sh=Be(),qz={keyword:"$ref",schemaType:"string",code(e){let{gen:t,schema:r,it:n}=e,{baseId:i,schemaEnv:o,validateName:a,opts:s,self:c}=n,{root:l}=o;if((r==="#"||r==="#/")&&i===l.baseId)return f();let u=$T.resolveRef.call(c,l,i,r);if(u===void 0)throw new Wz.default(n.opts.uriResolver,i,r);if(u instanceof $T.SchemaEnv)return d(u);return p(u);function f(){if(o===l)return ch(e,a,o,o.$async);let m=t.scopeValue("root",{ref:l});return ch(e,(0,en._)`${m}.validate`,l,l.$async)}function d(m){let h=DT(e,m);ch(e,h,m,m.$async)}function p(m){let h=t.scopeValue("schema",s.code.source===!0?{ref:m,code:(0,en.stringify)(m)}:{ref:m}),g=t.name("valid"),v=e.subschema({schema:m,dataTypes:[],schemaPath:en.nil,topSchemaRef:h,errSchemaPath:r},g);e.mergeEvaluated(v),e.ok(g)}}};function DT(e,t){let{gen:r}=e;return t.validate?r.scopeValue("validate",{ref:t.validate}):(0,en._)`${r.scopeValue("wrapper",{ref:t})}.validate`}ss.getValidate=DT;function ch(e,t,r,n){let{gen:i,it:o}=e,{allErrors:a,schemaEnv:s,opts:c}=o,l=c.passContext?Bc.default.this:en.nil;n?u():f();function u(){if(!s.$async)throw new Error("async schema referenced by sync schema");let m=i.let("valid");i.try(()=>{i.code((0,en._)`await ${(0,jT.callValidateCode)(e,t,l)}`),p(t),a||i.assign(m,!0)},h=>{i.if((0,en._)`!(${h} instanceof ${o.ValidationError})`,()=>i.throw(h)),d(h),a||i.assign(m,!1)}),e.ok(m)}function f(){e.result((0,jT.callValidateCode)(e,t,l),()=>p(t),()=>d(t))}function d(m){let h=(0,en._)`${m}.errors`;i.assign(Bc.default.vErrors,(0,en._)`${Bc.default.vErrors} === null ? ${h} : ${Bc.default.vErrors}.concat(${h})`),i.assign(Bc.default.errors,(0,en._)`${Bc.default.vErrors}.length`)}function p(m){var h;if(!o.opts.unevaluated)return;let g=(h=r?.validate)===null||h===void 0?void 0:h.evaluated;if(o.props!==!0)if(g&&!g.dynamicProps)g.props!==void 0&&(o.props=sh.mergeEvaluated.props(i,g.props,o.props));else{let v=i.var("props",(0,en._)`${m}.evaluated.props`);o.props=sh.mergeEvaluated.props(i,v,o.props,en.Name)}if(o.items!==!0)if(g&&!g.dynamicItems)g.items!==void 0&&(o.items=sh.mergeEvaluated.items(i,g.items,o.items));else{let v=i.var("items",(0,en._)`${m}.evaluated.items`);o.items=sh.mergeEvaluated.items(i,v,o.items,en.Name)}}}ss.callRef=ch;ss.default=qz});var WT=$(Mb=>{"use strict";Object.defineProperty(Mb,"__esModule",{value:!0});var Lz=OT(),Vz=BT(),Mz=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",Lz.default,Vz.default];Mb.default=Mz});var qT=$(Fb=>{"use strict";Object.defineProperty(Fb,"__esModule",{value:!0});var lh=Ce(),ca=lh.operators,uh={maximum:{okStr:"<=",ok:ca.LTE,fail:ca.GT},minimum:{okStr:">=",ok:ca.GTE,fail:ca.LT},exclusiveMaximum:{okStr:"<",ok:ca.LT,fail:ca.GTE},exclusiveMinimum:{okStr:">",ok:ca.GT,fail:ca.LTE}},Fz={message:({keyword:e,schemaCode:t})=>(0,lh.str)`must be ${uh[e].okStr} ${t}`,params:({keyword:e,schemaCode:t})=>(0,lh._)`{comparison: ${uh[e].okStr}, limit: ${t}}`},Hz={keyword:Object.keys(uh),type:"number",schemaType:"number",$data:!0,error:Fz,code(e){let{keyword:t,data:r,schemaCode:n}=e;e.fail$data((0,lh._)`${r} ${uh[t].fail} ${n} || isNaN(${r})`)}};Fb.default=Hz});var LT=$(Hb=>{"use strict";Object.defineProperty(Hb,"__esModule",{value:!0});var yd=Ce(),Qz={message:({schemaCode:e})=>(0,yd.str)`must be multiple of ${e}`,params:({schemaCode:e})=>(0,yd._)`{multipleOf: ${e}}`},Uz={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:Qz,code(e){let{gen:t,data:r,schemaCode:n,it:i}=e,o=i.opts.multipleOfPrecision,a=t.let("res"),s=o?(0,yd._)`Math.abs(Math.round(${a}) - ${a}) > 1e-${o}`:(0,yd._)`${a} !== parseInt(${a})`;e.fail$data((0,yd._)`(${n} === 0 || (${a} = ${r}/${n}, ${s}))`)}};Hb.default=Uz});var MT=$(Qb=>{"use strict";Object.defineProperty(Qb,"__esModule",{value:!0});function VT(e){let t=e.length,r=0,n=0,i;for(;n<t;)r++,i=e.charCodeAt(n++),i>=55296&&i<=56319&&n<t&&(i=e.charCodeAt(n),(i&64512)===56320&&n++);return r}Qb.default=VT;VT.code='require("ajv/dist/runtime/ucs2length").default'});var FT=$(Ub=>{"use strict";Object.defineProperty(Ub,"__esModule",{value:!0});var cs=Ce(),Jz=Be(),zz=MT(),Kz={message({keyword:e,schemaCode:t}){let r=e==="maxLength"?"more":"fewer";return(0,cs.str)`must NOT have ${r} than ${t} characters`},params:({schemaCode:e})=>(0,cs._)`{limit: ${e}}`},Gz={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:Kz,code(e){let{keyword:t,data:r,schemaCode:n,it:i}=e,o=t==="maxLength"?cs.operators.GT:cs.operators.LT,a=i.opts.unicode===!1?(0,cs._)`${r}.length`:(0,cs._)`${(0,Jz.useFunc)(e.gen,zz.default)}(${r})`;e.fail$data((0,cs._)`${a} ${o} ${n}`)}};Ub.default=Gz});var HT=$(Jb=>{"use strict";Object.defineProperty(Jb,"__esModule",{value:!0});var Yz=jn(),Xz=Be(),Wc=Ce(),Zz={message:({schemaCode:e})=>(0,Wc.str)`must match pattern "${e}"`,params:({schemaCode:e})=>(0,Wc._)`{pattern: ${e}}`},eK={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:Zz,code(e){let{gen:t,data:r,$data:n,schema:i,schemaCode:o,it:a}=e,s=a.opts.unicodeRegExp?"u":"";if(n){let{regExp:c}=a.opts.code,l=c.code==="new RegExp"?(0,Wc._)`new RegExp`:(0,Xz.useFunc)(t,c),u=t.let("valid");t.try(()=>t.assign(u,(0,Wc._)`${l}(${o}, ${s}).test(${r})`),()=>t.assign(u,!1)),e.fail$data((0,Wc._)`!${u}`)}else{let c=(0,Yz.usePattern)(e,i);e.fail$data((0,Wc._)`!${c}.test(${r})`)}}};Jb.default=eK});var QT=$(zb=>{"use strict";Object.defineProperty(zb,"__esModule",{value:!0});var kd=Ce(),tK={message({keyword:e,schemaCode:t}){let r=e==="maxProperties"?"more":"fewer";return(0,kd.str)`must NOT have ${r} than ${t} properties`},params:({schemaCode:e})=>(0,kd._)`{limit: ${e}}`},rK={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:tK,code(e){let{keyword:t,data:r,schemaCode:n}=e,i=t==="maxProperties"?kd.operators.GT:kd.operators.LT;e.fail$data((0,kd._)`Object.keys(${r}).length ${i} ${n}`)}};zb.default=rK});var UT=$(Kb=>{"use strict";Object.defineProperty(Kb,"__esModule",{value:!0});var bd=jn(),Ad=Ce(),nK=Be(),iK={message:({params:{missingProperty:e}})=>(0,Ad.str)`must have required property '${e}'`,params:({params:{missingProperty:e}})=>(0,Ad._)`{missingProperty: ${e}}`},oK={keyword:"required",type:"object",schemaType:"array",$data:!0,error:iK,code(e){let{gen:t,schema:r,schemaCode:n,data:i,$data:o,it:a}=e,{opts:s}=a;if(!o&&r.length===0)return;let c=r.length>=s.loopRequired;if(a.allErrors?l():u(),s.strictRequired){let p=e.parentSchema.properties,{definedProperties:m}=e.it;for(let h of r)if(p?.[h]===void 0&&!m.has(h)){let g=a.schemaEnv.baseId+a.errSchemaPath,v=`required property "${h}" is not defined at "${g}" (strictRequired)`;(0,nK.checkStrictMode)(a,v,a.opts.strictRequired)}}function l(){if(c||o)e.block$data(Ad.nil,f);else for(let p of r)(0,bd.checkReportMissingProp)(e,p)}function u(){let p=t.let("missing");if(c||o){let m=t.let("valid",!0);e.block$data(m,()=>d(p,m)),e.ok(m)}else t.if((0,bd.checkMissingProp)(e,r,p)),(0,bd.reportMissingProp)(e,p),t.else()}function f(){t.forOf("prop",n,p=>{e.setParams({missingProperty:p}),t.if((0,bd.noPropertyInData)(t,i,p,s.ownProperties),()=>e.error())})}function d(p,m){e.setParams({missingProperty:p}),t.forOf(p,n,()=>{t.assign(m,(0,bd.propertyInData)(t,i,p,s.ownProperties)),t.if((0,Ad.not)(m),()=>{e.error(),t.break()})},Ad.nil)}}};Kb.default=oK});var JT=$(Gb=>{"use strict";Object.defineProperty(Gb,"__esModule",{value:!0});var Rd=Ce(),aK={message({keyword:e,schemaCode:t}){let r=e==="maxItems"?"more":"fewer";return(0,Rd.str)`must NOT have ${r} than ${t} items`},params:({schemaCode:e})=>(0,Rd._)`{limit: ${e}}`},sK={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:aK,code(e){let{keyword:t,data:r,schemaCode:n}=e,i=t==="maxItems"?Rd.operators.GT:Rd.operators.LT;e.fail$data((0,Rd._)`${r}.length ${i} ${n}`)}};Gb.default=sK});var dh=$(Yb=>{"use strict";Object.defineProperty(Yb,"__esModule",{value:!0});var zT=hb();zT.code='require("ajv/dist/runtime/equal").default';Yb.default=zT});var KT=$(Zb=>{"use strict";Object.defineProperty(Zb,"__esModule",{value:!0});var Xb=cd(),sr=Ce(),cK=Be(),lK=dh(),uK={message:({params:{i:e,j:t}})=>(0,sr.str)`must NOT have duplicate items (items ## ${t} and ${e} are identical)`,params:({params:{i:e,j:t}})=>(0,sr._)`{i: ${e}, j: ${t}}`},dK={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:uK,code(e){let{gen:t,data:r,$data:n,schema:i,parentSchema:o,schemaCode:a,it:s}=e;if(!n&&!i)return;let c=t.let("valid"),l=o.items?(0,Xb.getSchemaTypes)(o.items):[];e.block$data(c,u,(0,sr._)`${a} === false`),e.ok(c);function u(){let m=t.let("i",(0,sr._)`${r}.length`),h=t.let("j");e.setParams({i:m,j:h}),t.assign(c,!0),t.if((0,sr._)`${m} > 1`,()=>(f()?d:p)(m,h))}function f(){return l.length>0&&!l.some(m=>m==="object"||m==="array")}function d(m,h){let g=t.name("item"),v=(0,Xb.checkDataTypes)(l,g,s.opts.strictNumbers,Xb.DataType.Wrong),w=t.const("indices",(0,sr._)`{}`);t.for((0,sr._)`;${m}--;`,()=>{t.let(g,(0,sr._)`${r}[${m}]`),t.if(v,(0,sr._)`continue`),l.length>1&&t.if((0,sr._)`typeof ${g} == "string"`,(0,sr._)`${g} += "_"`),t.if((0,sr._)`typeof ${w}[${g}] == "number"`,()=>{t.assign(h,(0,sr._)`${w}[${g}]`),e.error(),t.assign(c,!1).break()}).code((0,sr._)`${w}[${g}] = ${m}`)})}function p(m,h){let g=(0,cK.useFunc)(t,lK.default),v=t.name("outer");t.label(v).for((0,sr._)`;${m}--;`,()=>t.for((0,sr._)`${h} = ${m}; ${h}--;`,()=>t.if((0,sr._)`${g}(${r}[${m}], ${r}[${h}])`,()=>{e.error(),t.assign(c,!1).break(v)})))}}};Zb.default=dK});var GT=$(tA=>{"use strict";Object.defineProperty(tA,"__esModule",{value:!0});var eA=Ce(),fK=Be(),pK=dh(),mK={message:"must be equal to constant",params:({schemaCode:e})=>(0,eA._)`{allowedValue: ${e}}`},hK={keyword:"const",$data:!0,error:mK,code(e){let{gen:t,data:r,$data:n,schemaCode:i,schema:o}=e;n||o&&typeof o=="object"?e.fail$data((0,eA._)`!${(0,fK.useFunc)(t,pK.default)}(${r}, ${i})`):e.fail((0,eA._)`${o} !== ${r}`)}};tA.default=hK});var YT=$(rA=>{"use strict";Object.defineProperty(rA,"__esModule",{value:!0});var Nd=Ce(),gK=Be(),vK=dh(),wK={message:"must be equal to one of the allowed values",params:({schemaCode:e})=>(0,Nd._)`{allowedValues: ${e}}`},yK={keyword:"enum",schemaType:"array",$data:!0,error:wK,code(e){let{gen:t,data:r,$data:n,schema:i,schemaCode:o,it:a}=e;if(!n&&i.length===0)throw new Error("enum must have non-empty array");let s=i.length>=a.opts.loopEnum,c,l=()=>c??(c=(0,gK.useFunc)(t,vK.default)),u;if(s||n)u=t.let("valid"),e.block$data(u,f);else{if(!Array.isArray(i))throw new Error("ajv implementation error");let p=t.const("vSchema",o);u=(0,Nd.or)(...i.map((m,h)=>d(p,h)))}e.pass(u);function f(){t.assign(u,!1),t.forOf("v",o,p=>t.if((0,Nd._)`${l()}(${r}, ${p})`,()=>t.assign(u,!0).break()))}function d(p,m){let h=i[m];return typeof h=="object"&&h!==null?(0,Nd._)`${l()}(${r}, ${p}[${m}])`:(0,Nd._)`${r} === ${h}`}}};rA.default=yK});var XT=$(nA=>{"use strict";Object.defineProperty(nA,"__esModule",{value:!0});var kK=qT(),bK=LT(),AK=FT(),RK=HT(),NK=QT(),SK=UT(),EK=JT(),CK=KT(),_K=GT(),IK=YT(),xK=[kK.default,bK.default,AK.default,RK.default,NK.default,SK.default,EK.default,CK.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},_K.default,IK.default];nA.default=xK});var oA=$(Sd=>{"use strict";Object.defineProperty(Sd,"__esModule",{value:!0});Sd.validateAdditionalItems=void 0;var ls=Ce(),iA=Be(),PK={message:({params:{len:e}})=>(0,ls.str)`must NOT have more than ${e} items`,params:({params:{len:e}})=>(0,ls._)`{limit: ${e}}`},TK={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:PK,code(e){let{parentSchema:t,it:r}=e,{items:n}=t;if(!Array.isArray(n)){(0,iA.checkStrictMode)(r,'"additionalItems" is ignored when "items" is not an array of schemas');return}ZT(e,n)}};function ZT(e,t){let{gen:r,schema:n,data:i,keyword:o,it:a}=e;a.items=!0;let s=r.const("len",(0,ls._)`${i}.length`);if(n===!1)e.setParams({len:t.length}),e.pass((0,ls._)`${s} <= ${t.length}`);else if(typeof n=="object"&&!(0,iA.alwaysValidSchema)(a,n)){let l=r.var("valid",(0,ls._)`${s} <= ${t.length}`);r.if((0,ls.not)(l),()=>c(l)),e.ok(l)}function c(l){r.forRange("i",t.length,s,u=>{e.subschema({keyword:o,dataProp:u,dataPropType:iA.Type.Num},l),a.allErrors||r.if((0,ls.not)(l),()=>r.break())})}}Sd.validateAdditionalItems=ZT;Sd.default=TK});var aA=$(Ed=>{"use strict";Object.defineProperty(Ed,"__esModule",{value:!0});Ed.validateTuple=void 0;var eO=Ce(),fh=Be(),OK=jn(),jK={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(e){let{schema:t,it:r}=e;if(Array.isArray(t))return tO(e,"additionalItems",t);r.items=!0,!(0,fh.alwaysValidSchema)(r,t)&&e.ok((0,OK.validateArray)(e))}};function tO(e,t,r=e.schema){let{gen:n,parentSchema:i,data:o,keyword:a,it:s}=e;u(i),s.opts.unevaluated&&r.length&&s.items!==!0&&(s.items=fh.mergeEvaluated.items(n,r.length,s.items));let c=n.name("valid"),l=n.const("len",(0,eO._)`${o}.length`);r.forEach((f,d)=>{(0,fh.alwaysValidSchema)(s,f)||(n.if((0,eO._)`${l} > ${d}`,()=>e.subschema({keyword:a,schemaProp:d,dataProp:d},c)),e.ok(c))});function u(f){let{opts:d,errSchemaPath:p}=s,m=r.length,h=m===f.minItems&&(m===f.maxItems||f[t]===!1);if(d.strictTuples&&!h){let g=`"${a}" is ${m}-tuple, but minItems or maxItems/${t} are not specified or different at path "${p}"`;(0,fh.checkStrictMode)(s,g,d.strictTuples)}}}Ed.validateTuple=tO;Ed.default=jK});var rO=$(sA=>{"use strict";Object.defineProperty(sA,"__esModule",{value:!0});var $K=aA(),DK={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:e=>(0,$K.validateTuple)(e,"items")};sA.default=DK});var iO=$(cA=>{"use strict";Object.defineProperty(cA,"__esModule",{value:!0});var nO=Ce(),BK=Be(),WK=jn(),qK=oA(),LK={message:({params:{len:e}})=>(0,nO.str)`must NOT have more than ${e} items`,params:({params:{len:e}})=>(0,nO._)`{limit: ${e}}`},VK={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:LK,code(e){let{schema:t,parentSchema:r,it:n}=e,{prefixItems:i}=r;n.items=!0,!(0,BK.alwaysValidSchema)(n,t)&&(i?(0,qK.validateAdditionalItems)(e,i):e.ok((0,WK.validateArray)(e)))}};cA.default=VK});var oO=$(lA=>{"use strict";Object.defineProperty(lA,"__esModule",{value:!0});var Dn=Ce(),ph=Be(),MK={message:({params:{min:e,max:t}})=>t===void 0?(0,Dn.str)`must contain at least ${e} valid item(s)`:(0,Dn.str)`must contain at least ${e} and no more than ${t} valid item(s)`,params:({params:{min:e,max:t}})=>t===void 0?(0,Dn._)`{minContains: ${e}}`:(0,Dn._)`{minContains: ${e}, maxContains: ${t}}`},FK={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:MK,code(e){let{gen:t,schema:r,parentSchema:n,data:i,it:o}=e,a,s,{minContains:c,maxContains:l}=n;o.opts.next?(a=c===void 0?1:c,s=l):a=1;let u=t.const("len",(0,Dn._)`${i}.length`);if(e.setParams({min:a,max:s}),s===void 0&&a===0){(0,ph.checkStrictMode)(o,'"minContains" == 0 without "maxContains": "contains" keyword ignored');return}if(s!==void 0&&a>s){(0,ph.checkStrictMode)(o,'"minContains" > "maxContains" is always invalid'),e.fail();return}if((0,ph.alwaysValidSchema)(o,r)){let h=(0,Dn._)`${u} >= ${a}`;s!==void 0&&(h=(0,Dn._)`${h} && ${u} <= ${s}`),e.pass(h);return}o.items=!0;let f=t.name("valid");s===void 0&&a===1?p(f,()=>t.if(f,()=>t.break())):a===0?(t.let(f,!0),s!==void 0&&t.if((0,Dn._)`${i}.length > 0`,d)):(t.let(f,!1),d()),e.result(f,()=>e.reset());function d(){let h=t.name("_valid"),g=t.let("count",0);p(h,()=>t.if(h,()=>m(g)))}function p(h,g){t.forRange("i",0,u,v=>{e.subschema({keyword:"contains",dataProp:v,dataPropType:ph.Type.Num,compositeRule:!0},h),g()})}function m(h){t.code((0,Dn._)`${h}++`),s===void 0?t.if((0,Dn._)`${h} >= ${a}`,()=>t.assign(f,!0).break()):(t.if((0,Dn._)`${h} > ${s}`,()=>t.assign(f,!1).break()),a===1?t.assign(f,!0):t.if((0,Dn._)`${h} >= ${a}`,()=>t.assign(f,!0)))}}};lA.default=FK});var cO=$(xi=>{"use strict";Object.defineProperty(xi,"__esModule",{value:!0});xi.validateSchemaDeps=xi.validatePropertyDeps=xi.error=void 0;var uA=Ce(),HK=Be(),Cd=jn();xi.error={message:({params:{property:e,depsCount:t,deps:r}})=>{let n=t===1?"property":"properties";return(0,uA.str)`must have ${n} ${r} when property ${e} is present`},params:({params:{property:e,depsCount:t,deps:r,missingProperty:n}})=>(0,uA._)`{property: ${e},
|
|
192
|
+
missingProperty: ${n},
|
|
193
|
+
depsCount: ${t},
|
|
194
|
+
deps: ${r}}`};var QK={keyword:"dependencies",type:"object",schemaType:"object",error:xi.error,code(e){let[t,r]=UK(e);aO(e,t),sO(e,r)}};function UK({schema:e}){let t={},r={};for(let n in e){if(n==="__proto__")continue;let i=Array.isArray(e[n])?t:r;i[n]=e[n]}return[t,r]}function aO(e,t=e.schema){let{gen:r,data:n,it:i}=e;if(Object.keys(t).length===0)return;let o=r.let("missing");for(let a in t){let s=t[a];if(s.length===0)continue;let c=(0,Cd.propertyInData)(r,n,a,i.opts.ownProperties);e.setParams({property:a,depsCount:s.length,deps:s.join(", ")}),i.allErrors?r.if(c,()=>{for(let l of s)(0,Cd.checkReportMissingProp)(e,l)}):(r.if((0,uA._)`${c} && (${(0,Cd.checkMissingProp)(e,s,o)})`),(0,Cd.reportMissingProp)(e,o),r.else())}}xi.validatePropertyDeps=aO;function sO(e,t=e.schema){let{gen:r,data:n,keyword:i,it:o}=e,a=r.name("valid");for(let s in t)(0,HK.alwaysValidSchema)(o,t[s])||(r.if((0,Cd.propertyInData)(r,n,s,o.opts.ownProperties),()=>{let c=e.subschema({keyword:i,schemaProp:s},a);e.mergeValidEvaluated(c,a)},()=>r.var(a,!0)),e.ok(a))}xi.validateSchemaDeps=sO;xi.default=QK});var uO=$(dA=>{"use strict";Object.defineProperty(dA,"__esModule",{value:!0});var lO=Ce(),JK=Be(),zK={message:"property name must be valid",params:({params:e})=>(0,lO._)`{propertyName: ${e.propertyName}}`},KK={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:zK,code(e){let{gen:t,schema:r,data:n,it:i}=e;if((0,JK.alwaysValidSchema)(i,r))return;let o=t.name("valid");t.forIn("key",n,a=>{e.setParams({propertyName:a}),e.subschema({keyword:"propertyNames",data:a,dataTypes:["string"],propertyName:a,compositeRule:!0},o),t.if((0,lO.not)(o),()=>{e.error(!0),i.allErrors||t.break()})}),e.ok(o)}};dA.default=KK});var pA=$(fA=>{"use strict";Object.defineProperty(fA,"__esModule",{value:!0});var mh=jn(),ii=Ce(),GK=co(),hh=Be(),YK={message:"must NOT have additional properties",params:({params:e})=>(0,ii._)`{additionalProperty: ${e.additionalProperty}}`},XK={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:YK,code(e){let{gen:t,schema:r,parentSchema:n,data:i,errsCount:o,it:a}=e;if(!o)throw new Error("ajv implementation error");let{allErrors:s,opts:c}=a;if(a.props=!0,c.removeAdditional!=="all"&&(0,hh.alwaysValidSchema)(a,r))return;let l=(0,mh.allSchemaProperties)(n.properties),u=(0,mh.allSchemaProperties)(n.patternProperties);f(),e.ok((0,ii._)`${o} === ${GK.default.errors}`);function f(){t.forIn("key",i,g=>{!l.length&&!u.length?m(g):t.if(d(g),()=>m(g))})}function d(g){let v;if(l.length>8){let w=(0,hh.schemaRefOrVal)(a,n.properties,"properties");v=(0,mh.isOwnProperty)(t,w,g)}else l.length?v=(0,ii.or)(...l.map(w=>(0,ii._)`${g} === ${w}`)):v=ii.nil;return u.length&&(v=(0,ii.or)(v,...u.map(w=>(0,ii._)`${(0,mh.usePattern)(e,w)}.test(${g})`))),(0,ii.not)(v)}function p(g){t.code((0,ii._)`delete ${i}[${g}]`)}function m(g){if(c.removeAdditional==="all"||c.removeAdditional&&r===!1){p(g);return}if(r===!1){e.setParams({additionalProperty:g}),e.error(),s||t.break();return}if(typeof r=="object"&&!(0,hh.alwaysValidSchema)(a,r)){let v=t.name("valid");c.removeAdditional==="failing"?(h(g,v,!1),t.if((0,ii.not)(v),()=>{e.reset(),p(g)})):(h(g,v),s||t.if((0,ii.not)(v),()=>t.break()))}}function h(g,v,w){let y={keyword:"additionalProperties",dataProp:g,dataPropType:hh.Type.Str};w===!1&&Object.assign(y,{compositeRule:!0,createErrors:!1,allErrors:!1}),e.subschema(y,v)}}};fA.default=XK});var pO=$(hA=>{"use strict";Object.defineProperty(hA,"__esModule",{value:!0});var ZK=fd(),dO=jn(),mA=Be(),fO=pA(),eG={keyword:"properties",type:"object",schemaType:"object",code(e){let{gen:t,schema:r,parentSchema:n,data:i,it:o}=e;o.opts.removeAdditional==="all"&&n.additionalProperties===void 0&&fO.default.code(new ZK.KeywordCxt(o,fO.default,"additionalProperties"));let a=(0,dO.allSchemaProperties)(r);for(let f of a)o.definedProperties.add(f);o.opts.unevaluated&&a.length&&o.props!==!0&&(o.props=mA.mergeEvaluated.props(t,(0,mA.toHash)(a),o.props));let s=a.filter(f=>!(0,mA.alwaysValidSchema)(o,r[f]));if(s.length===0)return;let c=t.name("valid");for(let f of s)l(f)?u(f):(t.if((0,dO.propertyInData)(t,i,f,o.opts.ownProperties)),u(f),o.allErrors||t.else().var(c,!0),t.endIf()),e.it.definedProperties.add(f),e.ok(c);function l(f){return o.opts.useDefaults&&!o.compositeRule&&r[f].default!==void 0}function u(f){e.subschema({keyword:"properties",schemaProp:f,dataProp:f},c)}}};hA.default=eG});var vO=$(gA=>{"use strict";Object.defineProperty(gA,"__esModule",{value:!0});var mO=jn(),gh=Ce(),hO=Be(),gO=Be(),tG={keyword:"patternProperties",type:"object",schemaType:"object",code(e){let{gen:t,schema:r,data:n,parentSchema:i,it:o}=e,{opts:a}=o,s=(0,mO.allSchemaProperties)(r),c=s.filter(h=>(0,hO.alwaysValidSchema)(o,r[h]));if(s.length===0||c.length===s.length&&(!o.opts.unevaluated||o.props===!0))return;let l=a.strictSchema&&!a.allowMatchingProperties&&i.properties,u=t.name("valid");o.props!==!0&&!(o.props instanceof gh.Name)&&(o.props=(0,gO.evaluatedPropsToName)(t,o.props));let{props:f}=o;d();function d(){for(let h of s)l&&p(h),o.allErrors?m(h):(t.var(u,!0),m(h),t.if(u))}function p(h){for(let g in l)new RegExp(h).test(g)&&(0,hO.checkStrictMode)(o,`property ${g} matches pattern ${h} (use allowMatchingProperties)`)}function m(h){t.forIn("key",n,g=>{t.if((0,gh._)`${(0,mO.usePattern)(e,h)}.test(${g})`,()=>{let v=c.includes(h);v||e.subschema({keyword:"patternProperties",schemaProp:h,dataProp:g,dataPropType:gO.Type.Str},u),o.opts.unevaluated&&f!==!0?t.assign((0,gh._)`${f}[${g}]`,!0):!v&&!o.allErrors&&t.if((0,gh.not)(u),()=>t.break())})})}}};gA.default=tG});var wO=$(vA=>{"use strict";Object.defineProperty(vA,"__esModule",{value:!0});var rG=Be(),nG={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(e){let{gen:t,schema:r,it:n}=e;if((0,rG.alwaysValidSchema)(n,r)){e.fail();return}let i=t.name("valid");e.subschema({keyword:"not",compositeRule:!0,createErrors:!1,allErrors:!1},i),e.failResult(i,()=>e.reset(),()=>e.error())},error:{message:"must NOT be valid"}};vA.default=nG});var yO=$(wA=>{"use strict";Object.defineProperty(wA,"__esModule",{value:!0});var iG=jn(),oG={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:iG.validateUnion,error:{message:"must match a schema in anyOf"}};wA.default=oG});var kO=$(yA=>{"use strict";Object.defineProperty(yA,"__esModule",{value:!0});var vh=Ce(),aG=Be(),sG={message:"must match exactly one schema in oneOf",params:({params:e})=>(0,vh._)`{passingSchemas: ${e.passing}}`},cG={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:sG,code(e){let{gen:t,schema:r,parentSchema:n,it:i}=e;if(!Array.isArray(r))throw new Error("ajv implementation error");if(i.opts.discriminator&&n.discriminator)return;let o=r,a=t.let("valid",!1),s=t.let("passing",null),c=t.name("_valid");e.setParams({passing:s}),t.block(l),e.result(a,()=>e.reset(),()=>e.error(!0));function l(){o.forEach((u,f)=>{let d;(0,aG.alwaysValidSchema)(i,u)?t.var(c,!0):d=e.subschema({keyword:"oneOf",schemaProp:f,compositeRule:!0},c),f>0&&t.if((0,vh._)`${c} && ${a}`).assign(a,!1).assign(s,(0,vh._)`[${s}, ${f}]`).else(),t.if(c,()=>{t.assign(a,!0),t.assign(s,f),d&&e.mergeEvaluated(d,vh.Name)})})}}};yA.default=cG});var bO=$(kA=>{"use strict";Object.defineProperty(kA,"__esModule",{value:!0});var lG=Be(),uG={keyword:"allOf",schemaType:"array",code(e){let{gen:t,schema:r,it:n}=e;if(!Array.isArray(r))throw new Error("ajv implementation error");let i=t.name("valid");r.forEach((o,a)=>{if((0,lG.alwaysValidSchema)(n,o))return;let s=e.subschema({keyword:"allOf",schemaProp:a},i);e.ok(i),e.mergeEvaluated(s)})}};kA.default=uG});var NO=$(bA=>{"use strict";Object.defineProperty(bA,"__esModule",{value:!0});var wh=Ce(),RO=Be(),dG={message:({params:e})=>(0,wh.str)`must match "${e.ifClause}" schema`,params:({params:e})=>(0,wh._)`{failingKeyword: ${e.ifClause}}`},fG={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:dG,code(e){let{gen:t,parentSchema:r,it:n}=e;r.then===void 0&&r.else===void 0&&(0,RO.checkStrictMode)(n,'"if" without "then" and "else" is ignored');let i=AO(n,"then"),o=AO(n,"else");if(!i&&!o)return;let a=t.let("valid",!0),s=t.name("_valid");if(c(),e.reset(),i&&o){let u=t.let("ifClause");e.setParams({ifClause:u}),t.if(s,l("then",u),l("else",u))}else i?t.if(s,l("then")):t.if((0,wh.not)(s),l("else"));e.pass(a,()=>e.error(!0));function c(){let u=e.subschema({keyword:"if",compositeRule:!0,createErrors:!1,allErrors:!1},s);e.mergeEvaluated(u)}function l(u,f){return()=>{let d=e.subschema({keyword:u},s);t.assign(a,s),e.mergeValidEvaluated(d,a),f?t.assign(f,(0,wh._)`${u}`):e.setParams({ifClause:u})}}}};function AO(e,t){let r=e.schema[t];return r!==void 0&&!(0,RO.alwaysValidSchema)(e,r)}bA.default=fG});var SO=$(AA=>{"use strict";Object.defineProperty(AA,"__esModule",{value:!0});var pG=Be(),mG={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:e,parentSchema:t,it:r}){t.if===void 0&&(0,pG.checkStrictMode)(r,`"${e}" without "if" is ignored`)}};AA.default=mG});var EO=$(RA=>{"use strict";Object.defineProperty(RA,"__esModule",{value:!0});var hG=oA(),gG=rO(),vG=aA(),wG=iO(),yG=oO(),kG=cO(),bG=uO(),AG=pA(),RG=pO(),NG=vO(),SG=wO(),EG=yO(),CG=kO(),_G=bO(),IG=NO(),xG=SO();function PG(e=!1){let t=[SG.default,EG.default,CG.default,_G.default,IG.default,xG.default,bG.default,AG.default,kG.default,RG.default,NG.default];return e?t.push(gG.default,wG.default):t.push(hG.default,vG.default),t.push(yG.default),t}RA.default=PG});var CO=$(NA=>{"use strict";Object.defineProperty(NA,"__esModule",{value:!0});var _t=Ce(),TG={message:({schemaCode:e})=>(0,_t.str)`must match format "${e}"`,params:({schemaCode:e})=>(0,_t._)`{format: ${e}}`},OG={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:TG,code(e,t){let{gen:r,data:n,$data:i,schema:o,schemaCode:a,it:s}=e,{opts:c,errSchemaPath:l,schemaEnv:u,self:f}=s;if(!c.validateFormats)return;i?d():p();function d(){let m=r.scopeValue("formats",{ref:f.formats,code:c.code.formats}),h=r.const("fDef",(0,_t._)`${m}[${a}]`),g=r.let("fType"),v=r.let("format");r.if((0,_t._)`typeof ${h} == "object" && !(${h} instanceof RegExp)`,()=>r.assign(g,(0,_t._)`${h}.type || "string"`).assign(v,(0,_t._)`${h}.validate`),()=>r.assign(g,(0,_t._)`"string"`).assign(v,h)),e.fail$data((0,_t.or)(w(),y()));function w(){return c.strictSchema===!1?_t.nil:(0,_t._)`${a} && !${v}`}function y(){let R=u.$async?(0,_t._)`(${h}.async ? await ${v}(${n}) : ${v}(${n}))`:(0,_t._)`${v}(${n})`,N=(0,_t._)`(typeof ${v} == "function" ? ${R} : ${v}.test(${n}))`;return(0,_t._)`${v} && ${v} !== true && ${g} === ${t} && !${N}`}}function p(){let m=f.formats[o];if(!m){w();return}if(m===!0)return;let[h,g,v]=y(m);h===t&&e.pass(R());function w(){if(c.strictSchema===!1){f.logger.warn(N());return}throw new Error(N());function N(){return`unknown format "${o}" ignored in schema at path "${l}"`}}function y(N){let b=N instanceof RegExp?(0,_t.regexpCode)(N):c.code.formats?(0,_t._)`${c.code.formats}${(0,_t.getProperty)(o)}`:void 0,E=r.scopeValue("formats",{key:o,ref:N,code:b});return typeof N=="object"&&!(N instanceof RegExp)?[N.type||"string",N.validate,(0,_t._)`${E}.validate`]:["string",N,E]}function R(){if(typeof m=="object"&&!(m instanceof RegExp)&&m.async){if(!u.$async)throw new Error("async format in sync schema");return(0,_t._)`await ${v}(${n})`}return typeof g=="function"?(0,_t._)`${v}(${n})`:(0,_t._)`${v}.test(${n})`}}}};NA.default=OG});var _O=$(SA=>{"use strict";Object.defineProperty(SA,"__esModule",{value:!0});var jG=CO(),$G=[jG.default];SA.default=$G});var IO=$(qc=>{"use strict";Object.defineProperty(qc,"__esModule",{value:!0});qc.contentVocabulary=qc.metadataVocabulary=void 0;qc.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"];qc.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]});var PO=$(EA=>{"use strict";Object.defineProperty(EA,"__esModule",{value:!0});var DG=WT(),BG=XT(),WG=EO(),qG=_O(),xO=IO(),LG=[DG.default,BG.default,(0,WG.default)(),qG.default,xO.metadataVocabulary,xO.contentVocabulary];EA.default=LG});var OO=$(yh=>{"use strict";Object.defineProperty(yh,"__esModule",{value:!0});yh.DiscrError=void 0;var TO;(function(e){e.Tag="tag",e.Mapping="mapping"})(TO||(yh.DiscrError=TO={}))});var $O=$(_A=>{"use strict";Object.defineProperty(_A,"__esModule",{value:!0});var Lc=Ce(),CA=OO(),jO=Xm(),VG=pd(),MG=Be(),FG={message:({params:{discrError:e,tagName:t}})=>e===CA.DiscrError.Tag?`tag "${t}" must be string`:`value of tag "${t}" must be in oneOf`,params:({params:{discrError:e,tag:t,tagName:r}})=>(0,Lc._)`{error: ${e}, tag: ${r}, tagValue: ${t}}`},HG={keyword:"discriminator",type:"object",schemaType:"object",error:FG,code(e){let{gen:t,data:r,schema:n,parentSchema:i,it:o}=e,{oneOf:a}=i;if(!o.opts.discriminator)throw new Error("discriminator: requires discriminator option");let s=n.propertyName;if(typeof s!="string")throw new Error("discriminator: requires propertyName");if(n.mapping)throw new Error("discriminator: mapping is not supported");if(!a)throw new Error("discriminator: requires oneOf keyword");let c=t.let("valid",!1),l=t.const("tag",(0,Lc._)`${r}${(0,Lc.getProperty)(s)}`);t.if((0,Lc._)`typeof ${l} == "string"`,()=>u(),()=>e.error(!1,{discrError:CA.DiscrError.Tag,tag:l,tagName:s})),e.ok(c);function u(){let p=d();t.if(!1);for(let m in p)t.elseIf((0,Lc._)`${l} === ${m}`),t.assign(c,f(p[m]));t.else(),e.error(!1,{discrError:CA.DiscrError.Mapping,tag:l,tagName:s}),t.endIf()}function f(p){let m=t.name("valid"),h=e.subschema({keyword:"oneOf",schemaProp:p},m);return e.mergeEvaluated(h,Lc.Name),m}function d(){var p;let m={},h=v(i),g=!0;for(let R=0;R<a.length;R++){let N=a[R];if(N?.$ref&&!(0,MG.schemaHasRulesButRef)(N,o.self.RULES)){let E=N.$ref;if(N=jO.resolveRef.call(o.self,o.schemaEnv.root,o.baseId,E),N instanceof jO.SchemaEnv&&(N=N.schema),N===void 0)throw new VG.default(o.opts.uriResolver,o.baseId,E)}let b=(p=N?.properties)===null||p===void 0?void 0:p[s];if(typeof b!="object")throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${s}"`);g=g&&(h||v(N)),w(b,R)}if(!g)throw new Error(`discriminator: "${s}" must be required`);return m;function v({required:R}){return Array.isArray(R)&&R.includes(s)}function w(R,N){if(R.const)y(R.const,N);else if(R.enum)for(let b of R.enum)y(b,N);else throw new Error(`discriminator: "properties/${s}" must have "const" or "enum"`)}function y(R,N){if(typeof R!="string"||R in m)throw new Error(`discriminator: "${s}" values must be unique strings`);m[R]=N}}}};_A.default=HG});var DO=$((cie,QG)=>{QG.exports={$schema:"http://json-schema.org/draft-07/schema#",$id:"http://json-schema.org/draft-07/schema#",title:"Core schema meta-schema",definitions:{schemaArray:{type:"array",minItems:1,items:{$ref:"#"}},nonNegativeInteger:{type:"integer",minimum:0},nonNegativeIntegerDefault0:{allOf:[{$ref:"#/definitions/nonNegativeInteger"},{default:0}]},simpleTypes:{enum:["array","boolean","integer","null","number","object","string"]},stringArray:{type:"array",items:{type:"string"},uniqueItems:!0,default:[]}},type:["object","boolean"],properties:{$id:{type:"string",format:"uri-reference"},$schema:{type:"string",format:"uri"},$ref:{type:"string",format:"uri-reference"},$comment:{type:"string"},title:{type:"string"},description:{type:"string"},default:!0,readOnly:{type:"boolean",default:!1},examples:{type:"array",items:!0},multipleOf:{type:"number",exclusiveMinimum:0},maximum:{type:"number"},exclusiveMaximum:{type:"number"},minimum:{type:"number"},exclusiveMinimum:{type:"number"},maxLength:{$ref:"#/definitions/nonNegativeInteger"},minLength:{$ref:"#/definitions/nonNegativeIntegerDefault0"},pattern:{type:"string",format:"regex"},additionalItems:{$ref:"#"},items:{anyOf:[{$ref:"#"},{$ref:"#/definitions/schemaArray"}],default:!0},maxItems:{$ref:"#/definitions/nonNegativeInteger"},minItems:{$ref:"#/definitions/nonNegativeIntegerDefault0"},uniqueItems:{type:"boolean",default:!1},contains:{$ref:"#"},maxProperties:{$ref:"#/definitions/nonNegativeInteger"},minProperties:{$ref:"#/definitions/nonNegativeIntegerDefault0"},required:{$ref:"#/definitions/stringArray"},additionalProperties:{$ref:"#"},definitions:{type:"object",additionalProperties:{$ref:"#"},default:{}},properties:{type:"object",additionalProperties:{$ref:"#"},default:{}},patternProperties:{type:"object",additionalProperties:{$ref:"#"},propertyNames:{format:"regex"},default:{}},dependencies:{type:"object",additionalProperties:{anyOf:[{$ref:"#"},{$ref:"#/definitions/stringArray"}]}},propertyNames:{$ref:"#"},const:!0,enum:{type:"array",items:!0,minItems:1,uniqueItems:!0},type:{anyOf:[{$ref:"#/definitions/simpleTypes"},{type:"array",items:{$ref:"#/definitions/simpleTypes"},minItems:1,uniqueItems:!0}]},format:{type:"string"},contentMediaType:{type:"string"},contentEncoding:{type:"string"},if:{$ref:"#"},then:{$ref:"#"},else:{$ref:"#"},allOf:{$ref:"#/definitions/schemaArray"},anyOf:{$ref:"#/definitions/schemaArray"},oneOf:{$ref:"#/definitions/schemaArray"},not:{$ref:"#"}},default:!0}});var bh=$((ct,IA)=>{"use strict";Object.defineProperty(ct,"__esModule",{value:!0});ct.MissingRefError=ct.ValidationError=ct.CodeGen=ct.Name=ct.nil=ct.stringify=ct.str=ct._=ct.KeywordCxt=ct.Ajv=void 0;var UG=TT(),JG=PO(),zG=$O(),BO=DO(),KG=["/properties"],kh="http://json-schema.org/draft-07/schema",Vc=class extends UG.default{_addVocabularies(){super._addVocabularies(),JG.default.forEach(t=>this.addVocabulary(t)),this.opts.discriminator&&this.addKeyword(zG.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;let t=this.opts.$data?this.$dataMetaSchema(BO,KG):BO;this.addMetaSchema(t,kh,!1),this.refs["http://json-schema.org/schema"]=kh}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(kh)?kh:void 0)}};ct.Ajv=Vc;IA.exports=ct=Vc;IA.exports.Ajv=Vc;Object.defineProperty(ct,"__esModule",{value:!0});ct.default=Vc;var GG=fd();Object.defineProperty(ct,"KeywordCxt",{enumerable:!0,get:function(){return GG.KeywordCxt}});var Mc=Ce();Object.defineProperty(ct,"_",{enumerable:!0,get:function(){return Mc._}});Object.defineProperty(ct,"str",{enumerable:!0,get:function(){return Mc.str}});Object.defineProperty(ct,"stringify",{enumerable:!0,get:function(){return Mc.stringify}});Object.defineProperty(ct,"nil",{enumerable:!0,get:function(){return Mc.nil}});Object.defineProperty(ct,"Name",{enumerable:!0,get:function(){return Mc.Name}});Object.defineProperty(ct,"CodeGen",{enumerable:!0,get:function(){return Mc.CodeGen}});var YG=Gm();Object.defineProperty(ct,"ValidationError",{enumerable:!0,get:function(){return YG.default}});var XG=pd();Object.defineProperty(ct,"MissingRefError",{enumerable:!0,get:function(){return XG.default}})});var WO,qO=x(()=>{"use strict";WO=new Map});function Ah(e){let t=Ei(e),r=us.get(t);if(r)return us.delete(t),us.set(t,r),r;let i=WO.get(t)??new PA.Ajv({strict:!0,allErrors:!0}).compile(JSON.parse(t)),o={validate:i,errorsText:()=>PA.Ajv.prototype.errorsText(i.errors)};if(t.length<=LO){for(;us.size>=ZG||xA+t.length>LO;){let a=us.keys().next().value;us.delete(a),xA-=a.length}us.set(t,o),xA+=t.length}return o}var PA,ZG,LO,us,xA,TA=x(()=>{"use strict";PA=dr(bh(),1);qO();xr();ZG=128,LO=1024*1024,us=new Map,xA=0});function qt(e){throw new A("INVALID_WORKFLOW",e)}function la(e,t){return(e===null||typeof e!="object"||Array.isArray(e))&&qt(`${t} 必须是 JSON 对象`),e}function _d(e,t,r){for(let n of Object.keys(e))t.includes(n)||qt(`${r} 包含不支持的字段:${n}`)}function vr(e,t){return(typeof e!="string"||!e.trim()||e.length>4096)&&qt(`${t} 必须是非空字符串且不超过 4096 字符`),e}function OA(e,t,r=!1){(!Array.isArray(e)||!r&&e.length===0)&&qt(`${t} 必须是${r?"":"非空"}字符串数组`);let n=e.map(i=>vr(i,t));return new Set(n).size!==n.length&&qt(`${t} 不能包含重复值`),n}function jA(e,t){return OA(typeof e=="string"?[e]:e,t)}function Id(e,t){let r=la(e,t);return _d(r,["id","version"],t),{id:vr(r.id,`${t}.id`),version:vr(r.version,`${t}.version`)}}function MO(e){if(e!==null&&typeof e=="object"){for(let t of Object.values(e))MO(t);Object.freeze(e)}return e}function FO(e,t){try{let r=typeof e=="boolean"?e:la(e,t);typeof r!="boolean"&&r.$async===!0&&qt(`${t} 仅支持同步校验;异步检查请注册 RuntimeValidator`),Ah(r)}catch(r){qt(`${t} 不是受支持的 JSON Schema:${r.message}`)}}function tY(e){let t=la(e,"step"),r=vr(t.type,"step.type");["invoke_skill","call_tool","handoff","ask_user","child_workflow","await_evidence"].includes(r)||qt(`不支持的步骤类型:${r}`);let n=r==="ask_user"?["proposalFrom","choices"]:r==="child_workflow"?["workflow"]:r==="await_evidence"?["kind"]:[];_d(t,[...eY,...n],"step");let i=t.retry===void 0?"manual":t.retry;i!=="manual"&&i!=="idempotent"&&i!=="reconcile"&&qt("step.retry 必须是 manual、idempotent 或 reconcile");let o={...t.ref===void 0?{}:{ref:vr(t.ref,"step.ref")},...t.input===void 0?{}:{input:t.input},...t.outputSchema===void 0?{}:{outputSchema:t.outputSchema},...t.validator===void 0?{}:{validator:Id(t.validator,"step.validator")},...t.requiredCapabilities===void 0?{}:{requiredCapabilities:OA(t.requiredCapabilities,"step.requiredCapabilities",!0)},...t.join===void 0?{}:{join:OA(t.join,"step.join")},retry:i};return t.outputSchema!==void 0&&FO(t.outputSchema,"outputSchema"),r==="ask_user"?{...o,type:r,proposalFrom:jA(t.proposalFrom,"step.proposalFrom"),choices:jA(t.choices===void 0?["approved","rejected"]:t.choices,"step.choices")}:r==="child_workflow"?{...o,type:r,workflow:Id(t.workflow,"step.workflow")}:r==="await_evidence"?(o.validator||qt("await_evidence 必须声明验证器"),{...o,type:r,kind:vr(t.kind,"step.kind"),validator:o.validator}):{...o,type:r,ref:vr(t.ref,"step.ref")}}function Bn(e){if(VO.has(e))return e;let t=la(pt(e),"workflow");_d(t,["id","version","entry","steps","commands","transitions","maxTransitions","initialState","stateSchema","stateValidator","transitionHandler"],"workflow");let r=vr(t.id,"workflow.id"),n=vr(t.version,"workflow.version");t.initialState!==void 0&&t.stateSchema===void 0&&qt("workflow.initialState 必须声明 stateSchema"),t.stateValidator!==void 0&&t.stateSchema===void 0&&qt("workflow.stateValidator 必须声明 stateSchema"),t.stateSchema!==void 0&&FO(t.stateSchema,"stateSchema");let i=la(t.steps,"workflow.steps");Object.keys(i).length===0&&qt("workflow.steps 必须至少包含一个步骤");let o=Object.fromEntries(Object.entries(i).map(([h,g])=>(vr(h,"step id"),[h,tY(g)])));function a(h,g){Object.hasOwn(o,h)||qt(`${g} 引用了不存在的步骤:${h}`)}let s=jA(t.entry,"workflow.entry");for(let h of s)a(h,"workflow.entry");let c=t.commands===void 0?{}:la(t.commands,"workflow.commands"),l={};for(let[h,g]of Object.entries(c)){vr(h,"workflow command name");let v=typeof g=="string"?{stepId:vr(g,`workflow.commands.${h}`)}:la(g,`workflow.commands.${h}`);_d(v,["stepId","validator"],`workflow.commands.${h}`);let w=vr(v.stepId,`workflow.commands.${h}.stepId`);a(w,`workflow.commands.${h}`);let y=o[w];(y.join||!["invoke_skill","call_tool","handoff"].includes(y.type))&&qt(`workflow.commands.${h} 必须指向不带 join 的执行步骤`),Object.defineProperty(l,h,{value:{stepId:w,...v.validator===void 0?{}:{validator:Id(v.validator,`workflow.commands.${h}.validator`)}},enumerable:!0,configurable:!0,writable:!0})}let u=t.transitions===void 0?[]:t.transitions;Array.isArray(u)||qt("workflow.transitions 必须是数组");let f=new Set,d=u.map(h=>{let g=la(h,"transition");_d(g,["from","to","on"],"transition");let v=vr(g.from,"transition.from"),w=vr(g.to,"transition.to"),y=vr(g.on===void 0?"succeeded":g.on,"transition.on");a(v,"transition.from"),a(w,"transition.to");let R=JSON.stringify([v,w,y]);return f.has(R)&&qt(`重复的状态转移:${v} -> ${w} (${y})`),f.add(R),{from:v,to:w,on:y}});for(let[h,g]of Object.entries(o)){if(g.join){let v=new Set(d.filter(w=>w.to===h).map(w=>w.from));for(let w of g.join)a(w,`${h}.join`),v.has(w)||qt(`${h}.join 依赖缺少对应的进入边:${w}`);v.size!==g.join.length&&qt(`${h}.join 必须包含全部进入边的父节点`)}if(g.type==="ask_user")for(let v of g.proposalFrom)a(v,`${h}.proposalFrom`)}let p=t.maxTransitions===void 0?1e3:t.maxTransitions;(typeof p!="number"||!Number.isSafeInteger(p)||p<1)&&qt("workflow.maxTransitions 必须是正安全整数");let m=MO({id:r,version:n,entry:s,steps:o,...t.commands===void 0?{}:{commands:l},transitions:d,maxTransitions:p,...t.initialState===void 0?{}:{initialState:t.initialState},...t.stateSchema===void 0?{}:{stateSchema:t.stateSchema},...t.stateValidator===void 0?{}:{stateValidator:Id(t.stateValidator,"workflow.stateValidator")},...t.transitionHandler===void 0?{}:{transitionHandler:Id(t.transitionHandler,"workflow.transitionHandler")}});return VO.add(m),m}var eY,VO,$A=x(()=>{"use strict";_n();xr();TA();eY=["type","ref","input","outputSchema","validator","requiredCapabilities","retry","join"];VO=new WeakSet});function xd(e,t,r){Object.defineProperty(e,t,{value:r,configurable:!0,enumerable:!0,writable:!0})}function Rh(e){return Object.fromEntries(Object.entries(e).map(([t,r])=>[t,r.value]))}function rY(e){let t={};for(let r of e)for(let[n,i]of Object.entries(r.results))(!Object.hasOwn(t,n)||i.sequence>t[n].sequence)&&xd(t,n,i);return t}function uo(e,t){if(e.status==="cancelled"||e.status==="failed")return;for(;e.ready.length>0;){let o=e.ready.shift(),a=t.steps[o.to],s=o.results;if(a.join?.length){if(o.from===null||!a.join.includes(o.from))throw new A("INVALID_JOIN","join 必须由其声明的父节点触发");Object.hasOwn(e.joins,o.to)||xd(e.joins,o.to,Object.fromEntries(a.join.map(d=>[d,[]])));let f=e.joins[o.to];if(f[o.from].push(o),a.join.some(d=>f[d].length===0))continue;s=rY(a.join.map(d=>f[d].shift()))}if(e.sequence>=t.maxTransitions){e.ready.unshift(o),e.status="failed",e.reason="TRANSITION_LIMIT: 工作流已达到允许的步骤激活次数";return}let c=++e.sequence,l=`${e.runId}:${c}`,u={input:a.input===void 0?e.input:a.input,outputs:Rh(s),...o.activation===void 0?{}:{activation:o.activation}};if(a.type==="ask_user"){let f=Object.fromEntries(a.proposalFrom.map(p=>{if(!Object.hasOwn(s,p))throw new A("PROPOSAL_INPUT_MISSING",`确认步骤缺少上游产物:${p}`);return[p,s[p].value]})),d={input:u.input,outputs:f,...o.activation===void 0?{}:{activation:o.activation}};e.waits.push({id:l,stepId:o.to,sequence:c,status:"pending",proposal:d,proposalHash:D(d),choices:[...a.choices],results:s})}else if(a.type==="await_evidence")e.evidenceWaits??=[],e.evidenceWaits.push({id:l,stepId:o.to,sequence:c,kind:a.kind,status:"pending",results:s});else{let f=a.type==="child_workflow"?`${a.workflow.id}@${a.workflow.version}`:a.ref,d=Ix({id:l,runId:e.runId,stepId:o.to,type:a.type,ref:f,input:u,retry:a.retry,requiredCapabilities:a.requiredCapabilities});e.actions.push(d),xd(e.actionContexts,l,{sequence:c,results:s}),a.type==="child_workflow"&&e.children.push({actionId:l,runId:`child-${D(l)}`,workflow:a.workflow})}}let r=e.actions.some(o=>["pending","running","unknown"].includes(o.status)),n=e.waits.some(o=>o.status==="pending")||(e.evidenceWaits?.some(o=>o.status==="pending")??!1),i=Object.values(e.joins).some(o=>Object.values(o).some(a=>a.length>0));e.status=r?"running":n||i?"waiting":"completed"}function Fc(e,t,r,n,i,o,a,s){let c={sequence:n,value:o},l={...i};xd(l,r,c),(!Object.hasOwn(e.outputs,r)||e.outputs[r].sequence<=n)&&xd(e.outputs,r,c);let u=t.transitions.filter(p=>p.from===r),f=u.filter(p=>p.on===a),d=s??f.map(p=>p.to);if(d.length===0&&a==="failed"){e.status="failed",e.reason=`ACTION_FAILED: ${r}`;return}if(d.length===0&&s===void 0&&u.length>0)throw new A("TRANSITION_UNAVAILABLE",`步骤 ${r} 未声明 ${a} 的后续转换`);for(let p of d){let m=typeof p=="string"?p:p.stepId;if(!f.some(h=>h.to===m))throw new A("TRANSITION_TARGET_INVALID","后续步骤必须由工作流声明");e.ready.push({from:r,to:m,results:l,...typeof p=="string"?{}:{activation:p.input}})}}var HO=x(()=>{"use strict";Ka();_n();xr()});import{randomUUID as DA}from"node:crypto";import{types as qA}from"node:util";function QO(e){return Ye({runId:e.runId,revision:e.revision,status:e.status,sequence:e.sequence,workflow:e.workflow,input:e.input,...e.state===void 0?{}:{state:e.state},...e.reason===void 0?{}:{reason:e.reason},actions:e.actions.filter(t=>["pending","running","unknown"].includes(t.status)||t.status==="cancelled"&&t.claim&&!t.cancellation&&!t.executionStop),waits:e.waits.filter(t=>t.status==="pending"),evidenceWaits:(e.evidenceWaits??[]).filter(t=>t.status==="pending"),outputs:e.outputs,history:{actions:e.actions.length,waits:e.waits.length,evidenceWaits:e.evidenceWaits?.length??0}})}function mt(e){return JSON.stringify([e.id,e.version])}function gn(e){if(e===void 0)return;if(!e||typeof e!="object"||qA.isProxy(e))throw new A("INVALID_JSON","context 必须是普通对象");let t={},r;for(let i of Reflect.ownKeys(e)){let o=Object.getOwnPropertyDescriptor(e,i);if(typeof i!="string"||!o.enumerable||!("value"in o))throw new A("INVALID_JSON","context 必须使用普通数据属性");i==="signal"?r=o.value:o.value!==void 0&&Object.defineProperty(t,i,{value:o.value,enumerable:!0})}let n=pt(t);if(r!==void 0){if(!(r instanceof AbortSignal))throw new A("INVALID_JSON","signal 必须是 AbortSignal");n.signal=r}return n}function LA(e,t=new Set){if(e===null||typeof e!="object")return e;if(qA.isProxy(e))throw new A("INVALID_JSON","请求不能包含代理对象");if(t.size>64)throw new A("INVALID_JSON","请求数据嵌套超过 64 层");if(t.has(e))throw new A("INVALID_JSON","请求包含循环引用");let r=Object.getPrototypeOf(e);if(!Array.isArray(e)&&r!==Object.prototype&&r!==null)throw new A("INVALID_JSON","请求必须使用普通数据对象");t.add(e);let n=Array.isArray(e)?[]:{};for(let i of Reflect.ownKeys(e)){if(Array.isArray(e)&&i==="length")continue;let o=Object.getOwnPropertyDescriptor(e,i);if(typeof i!="string"||!o.enumerable||!("value"in o))throw new A("INVALID_JSON","请求必须使用普通数据属性");Object.defineProperty(n,i,{enumerable:!0,writable:!0,configurable:!0,value:LA(o.value,t)})}return t.delete(e),n}function BA(e){if(e===null||typeof e!="object")return e;if(qA.isProxy(e))throw new A("INVALID_JSON","请求不能包含代理对象");let t={};for(let r of Reflect.ownKeys(e)){let n=Object.getOwnPropertyDescriptor(e,r);if(typeof r!="string"||!n.enumerable||!("value"in n))throw new A("INVALID_JSON","请求必须使用普通数据属性");Object.defineProperty(t,r,{enumerable:!0,writable:!0,configurable:!0,value:r==="context"?gn(n.value):LA(n.value)})}return t}function ds(e){let t=LA(e),r=pt(t&&typeof t=="object"&&!Array.isArray(t)?Object.fromEntries(Object.entries(t).filter(([,n])=>n!==void 0)):t);if(!r||typeof r.accepted!="boolean"||r.reason!==void 0&&typeof r.reason!="string"||"allowCompleted"in r&&typeof r.allowCompleted!="boolean"||"allowFailed"in r&&typeof r.allowFailed!="boolean")throw new A("INVALID_VALIDATION","验证器必须返回布尔 accepted 和有效原因");return r}function WA(e,t){let r=e.supports(Ye(t));if(typeof r!="boolean")throw new A("INVALID_VALIDATION","执行器 supports 必须返回布尔值");return r}function Pi(e){if(e?.signal?.aborted)throw new A("REQUEST_ABORTED","请求已取消,请查询已提交状态后再决定是否重试")}function fs(e,t){if(e===t)return!0;if(!e||!t||typeof e!="object"||typeof t!="object"||Array.isArray(e)!==Array.isArray(t))return!1;let r=Object.keys(e);return r.length!==Object.keys(t).length?!1:r.every(n=>Object.hasOwn(t,n)&&fs(e[n],t[n]))}function UO(e){return{...e,definitionHashes:{...e.definitionHashes},actions:[...e.actions],...e.commands?{commands:[...e.commands]}:{},actionContexts:{...e.actionContexts},waits:e.waits.map(t=>({...t})),...e.evidenceWaits?{evidenceWaits:e.evidenceWaits.map(t=>({...t}))}:{},ready:[...e.ready],joins:Object.fromEntries(Object.entries(e.joins).map(([t,r])=>[t,Object.fromEntries(Object.entries(r).map(([n,i])=>[n,[...i]]))])),outputs:{...e.outputs},children:[...e.children],lineage:[...e.lineage]}}function wr(e){let t=new Map,r=new Map;for(let k of e.workflows){let C=Bn(k),j=mt(C);if(t.has(j))throw new A("DUPLICATE_WORKFLOW","不能重复注册同一工作流版本");t.set(j,C);let T=JO.get(C);T===void 0&&(T=D(C),JO.set(C,T)),r.set(C,T)}let n=new Map;for(let k of e.validators??[]){let C=mt(k);if(n.has(C))throw new A("DUPLICATE_VALIDATOR","不能重复注册同一验证器版本");n.set(C,k)}let i=new Map;for(let k of e.stateValidators??[]){let C=mt(k);if(i.has(C))throw new A("DUPLICATE_STATE_VALIDATOR","不能重复注册同一状态验证器版本");i.set(C,k)}let o=new Map;function a(k){let C=o.get(k);return C||(C=Ah(k),o.set(k,C)),C}let s=new Map,c=new Map;for(let k of e.transitionHandlers??[]){let C=mt(k);if(c.has(C))throw new A("DUPLICATE_TRANSITION_HANDLER","不能重复注册同一转移处理器版本");c.set(C,k)}let l=new Map;for(let k of e.evidenceValidators??[]){let C=mt(k);if(l.has(C))throw new A("DUPLICATE_EVIDENCE_VALIDATOR","不能重复注册同一证据验证器版本");l.set(C,k)}let u=new Map;for(let k of e.commandValidators??[]){let C=mt(k);if(u.has(C))throw new A("DUPLICATE_COMMAND_VALIDATOR","不能重复注册同一命令验证器版本");u.set(C,k)}for(let k of e.executors??[]){if(s.has(k.id))throw new A("DUPLICATE_EXECUTOR","不能重复注册同一执行器");s.set(k.id,k)}function f(k){let C=t.get(mt(k));if(!C)throw new A("WORKFLOW_UNAVAILABLE","请提供当前 Run 固定的工作流定义版本");if(k.hash!==void 0&&k.hash!==r.get(C))throw new A("WORKFLOW_CHANGED","同一版本的工作流内容已改变;请恢复原定义或显式迁移");return C}function d(k){if(k.transitionHandler&&!c.has(mt(k.transitionHandler)))throw new A("TRANSITION_HANDLER_UNAVAILABLE","未注册工作流所要求的转移处理器版本")}function p(k){if(k.stateValidator&&!i.has(mt(k.stateValidator)))throw new A("STATE_VALIDATOR_UNAVAILABLE","未注册工作流所要求的状态验证器版本")}function m(k){for(let C of Object.values(k.steps))if(C.type==="await_evidence"&&!l.has(mt(C.validator)))throw new A("EVIDENCE_VALIDATOR_UNAVAILABLE","未注册工作流所要求的证据验证器版本")}function h(k){for(let C of Object.values(k.commands??{}))if(C.validator&&!u.has(mt(C.validator)))throw new A("COMMAND_VALIDATOR_UNAVAILABLE","未注册工作流所要求的命令验证器版本")}function g(k,C,j){if(k.stateSchema!==void 0){let T=a(k.stateSchema);if(!T.validate(C))throw new A(j,T.errorsText())}if(k.stateValidator){let T=i.get(mt(k.stateValidator));if(!T)throw new A("STATE_VALIDATOR_UNAVAILABLE","未注册工作流所要求的状态验证器版本");try{let O=ds(T.validate({state:pt(C)}));if(!O.accepted)throw new Error(O.reason??"业务状态未通过验证")}catch(O){throw new A(j,O instanceof Error?O.message:String(O))}}}function v(k,C,j,T){if(!C.transitionHandler)return;let O=c.get(mt(C.transitionHandler));if(!O)throw new A("TRANSITION_HANDLER_UNAVAILABLE","未注册工作流所要求的转移处理器版本");let J=pt(O.apply({run:Ye(k),event:Ye(j)})),K=pt(J.state);g(C,K,"TRANSITION_STATE_INVALID");let Y=new Set(C.transitions.filter(ce=>ce.from===j.stepId&&ce.on===T).map(ce=>ce.to));if(!Array.isArray(J.next))throw new A("TRANSITION_TARGET_INVALID","转移处理器选择了未声明或重复的后续步骤");let z=[],X=new Set;for(let ce of J.next){let L;if(typeof ce=="string")L=ce;else if(ce!==null&&typeof ce=="object"&&!Array.isArray(ce)){let Re=Object.keys(ce);if(Re.length!==2||!Re.includes("stepId")||!Re.includes("input")||typeof ce.stepId!="string")throw new A("TRANSITION_TARGET_INVALID","后续步骤的输入绑定无效");L={stepId:ce.stepId,input:pt(ce.input)}}else throw new A("TRANSITION_TARGET_INVALID","后续步骤的输入绑定无效");let ge=typeof L=="string"?L:L.stepId,oe=D(L);if(!Y.has(ge)||X.has(oe))throw new A("TRANSITION_TARGET_INVALID","转移处理器选择了未声明或重复的后续步骤");X.add(oe),z.push(L)}return k.state=K,z}function w(k,C=D){if(t.size>0)for(let[j,T]of Object.entries(k.definitionHashes)){let[O,J]=JSON.parse(j),K=f({id:O,version:J,hash:T});if(d(K),p(K),m(K),h(K),O===k.workflow.id&&J===k.workflow.version){let Y=new Map(k.actions.map(z=>[z.id,z]));for(let z of k.commands??[]){let X=Y.get(z.actionId),ce=Object.hasOwn(K.commands??{},z.name),L=X&&!ce&&!Object.hasOwn(K.steps,X.stepId)&&["succeeded","failed","cancelled"].includes(X.status);if(!X||!L&&(!ce||K.commands?.[z.name].stepId!==X.stepId)||X.input===null||typeof X.input!="object"||!Object.hasOwn(X.input,"activation")||C(X.input.activation)!==z.inputHash)throw new A("INVALID_RUN","命令记录与固定工作流 Action 不一致")}if(K.stateSchema!==void 0&&K.initialState===void 0&&k.initialStateHash===void 0)throw new A("INVALID_RUN","已保存的 Run 缺少启动时的初始状态绑定");g(K,k.state,"RUN_STATE_INVALID");for(let z of k.ready){let X=()=>{throw new A("INVALID_RUN","待调度步骤与固定工作流定义不一致")};if(Object.hasOwn(K.steps,z.to)||X(),z.from===null){(!K.entry.includes(z.to)||Object.keys(z.results).length>0||k.sequence!==0&&!(k.status==="failed"&&k.reason?.startsWith("TRANSITION_LIMIT:")))&&X();continue}let ce=z.results[z.from];ce||X();let L=k.actions.find(Fr=>Fr.stepId===z.from&&k.actionContexts[Fr.id].sequence===ce.sequence),ge=k.waits.find(Fr=>Fr.stepId===z.from&&Fr.sequence===ce.sequence),oe=k.evidenceWaits?.find(Fr=>Fr.stepId===z.from&&Fr.sequence===ce.sequence),Re=L?.outcome?L.outcome.status==="failed"?"failed":L.outcome.event??"succeeded":ge?.decision?.choice??(oe?.invalidation?"invalidated":oe?.receipt?"succeeded":void 0),vt=L?k.actionContexts[L.id].results:ge?.results??oe?.results,Ql=L?.outcome?L.outcome.output:ge?.decision?{choice:ge.decision.choice,proposal:ge.proposal}:oe?.invalidation?{ref:oe.invalidation.ref,contentHash:oe.invalidation.contentHash,reason:oe.invalidation.reason}:oe?.receipt?{ref:oe.receipt.ref,contentHash:oe.receipt.contentHash}:void 0;(!Re||!vt||L&&!["succeeded","failed"].includes(L.status)||ge&&ge.status!=="resolved"||oe&&!["resolved","invalidated"].includes(oe.status)||Ql===void 0||C(z.results)!==C({...vt,[z.from]:{sequence:ce.sequence,value:Ql}})||!K.transitions.some(Fr=>Fr.from===z.from&&Fr.to===z.to&&Fr.on===Re))&&X()}for(let z of k.evidenceWaits??[]){let X=K.steps[z.stepId];if(!(!X&&z.status!=="pending")&&(!X||X.type!=="await_evidence"||X.kind!==z.kind))throw new A("INVALID_RUN","已保存的证据等待项与固定工作流定义不一致")}}}}async function y(k){let C=await e.store.read(k);if(!C)throw new A("RUN_NOT_FOUND",`找不到工作流实例:${k}`);let j=Jx(C,k);return w(j),za(j)}async function R(k,C,j){for(let T=0;T<32;T+=1){Pi(k.context);let O=T===0&&j?j:await y(k.runId),J=f(O.workflow);if(k.expectedRevision!==void 0&&k.expectedRevision!==O.revision)throw new A("REVISION_CONFLICT","Run 已变化,请重新读取当前状态");let K=UO(O);if(await C(K,J),xn(K),fs(K,O))return O;if(K.revision=O.revision+1,Dm(K,O),w(K),za(K),Pi(k.context),await e.store.compareAndSwap(k.runId,O.revision,K))return K}throw new A("REVISION_CONFLICT","并发提交持续冲突,请重新读取当前状态")}function N(k,C){let j=k.actions.find(T=>T.id===C);if(!j)throw new A("ACTION_NOT_FOUND","Run 不包含此 Action");return j}function b(k){if(k.status==="cancelled")throw new A("RUN_CANCELLED","Run 已取消,不能继续推进")}function E(k,C={}){let j=mt(k);if(Object.hasOwn(C,j))return C;C[j]=r.get(k);for(let T of Object.values(k.steps))T.type==="child_workflow"&&E(f(T.workflow),C);return C}async function I(k,C){if(Pi(k.context),C.length>32)throw new A("CHILD_DEPTH_LIMIT","子工作流嵌套超过 32 层");let j=f(k.workflow);d(j),p(j),m(j),h(j);let T=Object.hasOwn(k,"initialState");if(T&&j.initialState!==void 0)throw new A("INITIAL_STATE_CONFLICT","工作流定义和启动请求不能同时指定初始状态");let O=T?pt(k.initialState):j.initialState;if(j.stateSchema!==void 0&&O===void 0)throw new A("INITIAL_STATE_REQUIRED","启动请求必须提供工作流初始状态");O!==void 0&&g(j,O,"INITIAL_STATE_INVALID");let J=O===void 0?void 0:D(O),K=k.runId??DA(),Y=pt(k.input),z={id:j.id,version:j.version,hash:r.get(j)},X=await e.store.read(K);if(X){if(D(X.workflow)!==D(z)||D(X.input)!==D(Y)||D(X.lineage)!==D(C)||(X.initialStateHash??(j.initialState===void 0?void 0:D(j.initialState)))!==J)throw new A("RUN_CONFLICT","该 Run 标识已绑定不同工作流或输入");return y(K)}let ce={protocolVersion:1,schemaVersion:1,runId:K,revision:1,workflow:z,definitionHashes:E(j),input:Y,...O===void 0?{}:{state:pt(O),initialStateHash:J},status:"running",sequence:0,actions:[],actionContexts:{},waits:[],ready:j.entry.map(L=>({from:null,to:L,results:{}})),joins:{},outputs:{},children:[],lineage:C};return uo(ce,j),za(ce),Pi(k.context),Dm(ce),w(ce),await e.store.compareAndSwap(K,null,ce)?Ye(ce):I({...k,runId:K},C)}async function W(k){return I(k,[])}async function F(k){let C=pt(k.input),j=D(C);if(!k.commandId.trim()||k.commandId.length>4096||!k.name.trim()||k.name.length>4096)throw new A("INVALID_COMMAND","命令标识和名称不能为空");for(let T=0;T<32;T+=1){Pi(k.context);let O=await y(k.runId),J=O.commands?.find(oe=>oe.id===k.commandId);if(J){if(J.name!==k.name||J.inputHash!==j)throw new A("COMMAND_CONFLICT","同一命令标识不能提交不同内容");return O}if(k.expectedRevision!==O.revision)throw new A("REVISION_CONFLICT","Run 已变化,请重新读取当前状态");let K=f(O.workflow),Y=Object.hasOwn(K.commands??{},k.name)?K.commands?.[k.name]:void 0;if(!Y)throw new A("COMMAND_NOT_FOUND","工作流未声明此命令");let z=Y.stepId;if(O.status==="cancelled")throw new A("RUN_TERMINAL","已停止的 Run 不能接受命令");if(O.actions.some(oe=>["running","unknown"].includes(oe.status)))throw new A("ACTION_IN_FLIGHT","已有 Action 的执行结果不明,不能中断");let X=!1,ce=!1;if(Y.validator){let oe=u.get(mt(Y.validator));if(!oe)throw new A("COMMAND_VALIDATOR_UNAVAILABLE","未注册工作流所要求的命令验证器版本");let Re;try{Re=ds(await oe.validate({run:Ye(O),name:k.name,input:Ye(C),context:gn(k.context)}))}catch(vt){throw new A("COMMAND_VALIDATION_ERROR",vt instanceof Error?vt.message:String(vt))}if(X=Re.accepted&&Re.allowCompleted===!0,ce=Re.accepted&&Re.allowFailed===!0,O.status==="failed"&&!ce)throw new A("RUN_TERMINAL","已停止的 Run 不能接受命令");if(O.status==="completed"&&!X)throw new A("RUN_TERMINAL","已停止的 Run 不能接受命令");if(!Re.accepted)throw new A("COMMAND_REJECTED",Re.reason??"命令未通过当前工作流状态验证")}if(O.status==="completed"&&!X)throw new A("RUN_TERMINAL","已停止的 Run 不能接受命令");if(O.status==="failed"&&!ce)throw new A("RUN_TERMINAL","已停止的 Run 不能接受命令");let L=Ye(O);O.status==="failed"&&(L.status="running",delete L.reason),L.actions=L.actions.map(oe=>oe.status==="pending"?_m(oe,`命令 ${k.name} 已取代待执行 Action`):oe);for(let oe of L.waits)oe.status==="pending"&&(oe.status="cancelled");for(let oe of L.evidenceWaits??[])oe.status==="pending"&&(oe.status="cancelled");L.ready=[{from:null,to:z,results:{},activation:C}],L.joins={},uo(L,K);let ge=L.actions.at(-1);if(!ge||ge.stepId!==z||ge.status!=="pending")throw new A("COMMAND_DISPATCH_FAILED","命令未生成可执行的 Action");if(L.commands=[...L.commands??[],{id:k.commandId,name:k.name,inputHash:j,actionId:ge.id}],L.revision=O.revision+1,Dm(L,O),w(L),za(L),Pi(k.context),await e.store.compareAndSwap(k.runId,O.revision,L))return Ye(L)}throw new A("REVISION_CONFLICT","并发提交持续冲突,请重新读取当前状态")}async function G(k){for(let C of k.children)await e.store.read(C.runId)&&await P({runId:C.runId,reason:k.reason??"父工作流已取消"})}function Z(k,C,j){let T=f(k.workflow),O=Object.hasOwn(T.steps,j.stepId)?T.steps[j.stepId]:void 0;if(!O||O.type!=="child_workflow"||mt(O.workflow)!==mt(C.workflow)||j.type!==O.type||j.ref!==`${O.workflow.id}@${O.workflow.version}`||j.attempt!==1||j.retry!==O.retry||!fs(j.requiredCapabilities,O.requiredCapabilities??[])||j.claim&&(j.claim.executorId!=="comet-child-workflow"||j.claim.sessionId!==void 0||![C.runId,`portable-${D(C.runId)}`].includes(j.claim.token)))throw new A("INVALID_RUN","子工作流 Action 与固定定义或 Runtime 领取身份不一致");let J=j.input;if(!J||typeof J!="object"||Array.isArray(J)||!fs(J,{input:O.input===void 0?k.input:O.input,outputs:Rh(k.actionContexts[j.id].results),...Object.hasOwn(J,"activation")?{activation:J.activation}:{}}))throw new A("INVALID_RUN","子工作流 Action 输入与父 Run 上下文不一致");let K=f({...C.workflow,hash:k.definitionHashes[mt(C.workflow)]});if(Object.entries(E(K)).some(([Y,z])=>k.definitionHashes[Y]!==z))throw new A("INVALID_RUN","父 Run 缺少子工作流的固定定义绑定");return K}function Ae(k,C,j,T,O){let J=T.initialState===void 0?void 0:D(T.initialState);if(O.runId!==C.runId||mt(O.workflow)!==mt(C.workflow)||O.workflow.hash!==k.definitionHashes[mt(C.workflow)]||!fs(O.definitionHashes,E(T))||!fs(O.input,j.input)||!fs(O.lineage,[...k.lineage,k.runId])||(O.initialStateHash??J)!==J)throw new A("RUN_CONFLICT","已有子 Run 与父 Action 的固定定义、输入或归属不一致")}async function re(k){let C=await R(k,(j,T)=>uo(j,T));if(C.status==="cancelled")return await G(C),C;if(C.status==="failed"||C.children.length===0)return C;for(let j of C.children){let T=N(C,j.actionId);if(!["pending","running","unknown"].includes(T.status))continue;let O=Z(C,j,T);T.status==="pending"&&(C=await nt({runId:C.runId,actionId:T.id,attempt:T.attempt,inputHash:T.inputHash,executorId:"comet-child-workflow",claimToken:j.runId,capabilities:["child-workflow"],context:gn(k.context)},!0),T=N(C,j.actionId));let J=T.status==="unknown"?await y(j.runId):await I({runId:j.runId,workflow:j.workflow,input:T.input,context:gn(k.context)},[...C.lineage,C.runId]);Ae(C,j,T,O,J);let K=await y(C.runId);if(K.status==="cancelled")return await G(K),K;let Y=await re({runId:j.runId,context:k.context});Ae(C,j,T,O,Y),["completed","failed","cancelled"].includes(Y.status)&&(C=await q({runId:C.runId,context:gn(k.context),outcome:{actionId:T.id,attempt:T.attempt,inputHash:T.inputHash,claimToken:T.claim.token,outcomeId:`${j.runId}:${Y.revision}`,status:Y.status==="completed"?"succeeded":"failed",output:Rh(Y.outputs)}},!0))}return y(C.runId)}async function nt(k,C=!1,j){let T=k.claimToken??(k.context?.requestId?D({runId:k.runId,actionId:k.actionId,attempt:k.attempt,executorId:k.executorId,requestId:k.context.requestId}):DA());return R(k,async O=>{if(b(O),O.status==="failed")throw new A("RUN_FAILED","Run 已因失败停止;请先完成显式恢复");let J=N(O,k.actionId);if(J.type==="child_workflow"&&!C)throw new A("CHILD_MANAGED","子工作流由 Runtime 登记与核对,不接受宿主代领");let K=Tk(J,{executionOrigin:{workflow:{...O.workflow}},attempt:k.attempt,inputHash:k.inputHash,executorId:k.executorId,token:T,...k.sessionId===void 0?{}:{sessionId:k.sessionId}});if(!J.claim){let Y=new Set(k.capabilities??[]);if(J.requiredCapabilities.some(X=>!Y.has(X)))throw new A("CAPABILITY_REQUIRED","执行者未声明 Action 要求的全部宿主能力");let z=s.get(k.executorId);if(z&&WA(z,J)){if(J.requiredCapabilities.some(X=>!z.capabilities.includes(X)))throw new A("CAPABILITY_REQUIRED","已配置执行端口缺少 Action 要求的宿主能力");await z.preflight?.(Ye(J),gn(k.context),z.includeRun===!1?void 0:Ye(O)),Pi(k.context)}}O.actions[O.actions.indexOf(J)]=K},j)}async function rr(k){return nt(k)}async function q(k,C=!1,j){let T,O;try{T=Im(k.outcome)}catch(Y){O=Y}k={...k,outcome:T};let J,K=await R(k,async(Y,z)=>{if(J=void 0,b(Y),!T)throw O;let X=N(Y,k.outcome.actionId);if(X.type==="child_workflow"&&!C)throw new A("CHILD_MANAGED","子工作流结果必须由 Runtime 读取其已提交状态");let ce=Cm(X,k.outcome);if(ce.duplicate)return;let L=ce.action.outcome,ge=Y.actions.indexOf(X);try{if(e.validateOutcome){let Re=ds(await e.validateOutcome({run:Ye(Y),action:Ye(X),outcome:Ye(L),context:gn(k.context)}));Re.accepted||(J={code:"OUTCOME_REJECTED",reason:Re.reason??"应用结果契约拒绝此结果"})}let oe=z.steps[X.stepId];if(!J&&L.status==="succeeded"&&oe.outputSchema!==void 0){let Re=a(oe.outputSchema);Re.validate(L.output)||(J={code:"OUTPUT_INVALID",reason:Re.errorsText()})}if(!J&&oe.validator){let Re=n.get(mt(oe.validator));if(!Re)throw new A("VALIDATOR_UNAVAILABLE","未注册工作流所要求的验证器版本");let vt=ds(await Re.validate({run:Ye(Y),action:Ye(X),outcome:Ye(L),context:gn(k.context)}));vt.accepted||(J={code:"OUTCOME_REJECTED",reason:vt.reason?.trim()?vt.reason:"结果未满足业务验收条件"})}if(!J){let Re=UO(Y);Re.actions[ge]=ce.action;let vt=Re.actionContexts[X.id],Ql=L.status==="failed"?"failed":L.event??"succeeded",Fr=v(Re,z,{kind:"action-outcome",stepId:X.stepId,outcome:L},Ql);Fc(Re,z,X.stepId,vt.sequence,vt.results,L.output,Ql,Fr),uo(Re,z),Object.assign(Y,Re)}}catch(oe){J={code:"OUTCOME_PROCESSING_ERROR",reason:oe instanceof Error&&oe.message.trim()?oe.message:"结果处理失败,请检查验证器或工作流定义"}}J&&(Y.actions[ge]={...X,receipts:ce.action.receipts,rejectedOutcomes:[...X.rejectedOutcomes??[],{outcome:ce.action.outcome,...J}]})},j);if(J)throw new A(J.code,J.reason);return K}async function ne(k){return q(k)}async function he(k){if(k.reason!==void 0&&!Dk(k.reason))throw new A("INVALID_DECISION","reason 必须是 1 到 4096 字符的非空文本");return R(k,(C,j)=>{b(C);let T=C.waits.find(J=>J.id===k.waitId);if(!T)throw new A("WAIT_NOT_FOUND","Run 不包含此等待项");if(T.decision){if(T.decision.id!==k.decisionId||T.decision.choice!==k.choice||T.decision.proposalHash!==k.proposalHash||T.decision.reason!==k.reason)throw new A("DECISION_CONFLICT","等待项已经接受了不同的决定");return}if(T.status!=="pending"||T.proposalHash!==k.proposalHash)throw new A("STALE_PROPOSAL","提案已改变或等待项已终止,请重新审阅");if(!k.decisionId.trim()||!T.choices.includes(k.choice))throw new A("INVALID_DECISION","决定标识或选择不符合当前等待项");T.status="resolved",T.decision={id:k.decisionId,choice:k.choice,proposalHash:k.proposalHash,...k.reason===void 0?{}:{reason:k.reason}};let O=v(C,j,{kind:"wait-resolved",stepId:T.stepId,choice:k.choice,proposalHash:k.proposalHash,decisionId:k.decisionId},k.choice);Fc(C,j,T.stepId,T.sequence,T.results,{choice:k.choice,proposal:T.proposal},k.choice,O),uo(C,j)})}async function Ot(k){return R(k,async(C,j)=>{if(b(C),C.status==="failed")throw new A("RUN_FAILED","Run 已因失败停止,不能提交证据");let T=C.evidenceWaits?.find(z=>z.id===k.evidenceId);if(!T)throw new A("EVIDENCE_WAIT_NOT_FOUND","Run 不包含此证据等待项");if(T.status!=="pending")throw new A("EVIDENCE_WAIT_RESOLVED","证据等待项已结束");if(T.kind!==k.kind)throw new A("EVIDENCE_KIND_MISMATCH","证据种类与等待项不一致");if(!k.ref.trim()||/^(?:[a-zA-Z]:|[\\/~])/u.test(k.ref)||k.ref.split(/[\\/]/u).includes("..")||!/^[a-f0-9]{64}$/u.test(k.contentHash)||!k.submissionId.trim())throw new A("INVALID_EVIDENCE","证据引用、摘要或提交标识无效");let O=j.steps[T.stepId];if(!O||O.type!=="await_evidence"||O.kind!==k.kind)throw new A("EVIDENCE_STEP_CHANGED","证据等待项与固定工作流不一致");let J=l.get(mt(O.validator));if(!J)throw new A("EVIDENCE_VALIDATOR_UNAVAILABLE","未注册证据验证器版本");let K=ds(await J.validate({run:Ye(C),kind:k.kind,ref:k.ref,contentHash:k.contentHash,context:gn(k.context)}));if(!K.accepted||K.actualHash!==k.contentHash)throw new A("EVIDENCE_REJECTED",K.reason??"证据未通过验证或内容已改变");T.status="resolved",T.receipt={ref:k.ref,contentHash:k.contentHash,submissionId:k.submissionId};let Y=v(C,j,{kind:"evidence-recorded",stepId:T.stepId,evidenceKind:k.kind,ref:k.ref,contentHash:k.contentHash,submissionId:k.submissionId},"succeeded");Fc(C,j,T.stepId,T.sequence,T.results,{ref:k.ref,contentHash:k.contentHash},"succeeded",Y),uo(C,j)})}async function _(k){return R(k,async(C,j)=>{if(b(C),C.status==="failed")throw new A("RUN_FAILED","Run 已因失败停止,不能使证据失效");let T=C.evidenceWaits?.find(X=>X.id===k.evidenceId);if(!T)throw new A("EVIDENCE_WAIT_NOT_FOUND","Run 不包含此证据等待项");if(T.status!=="pending")throw new A("EVIDENCE_WAIT_RESOLVED","证据等待项已结束");if(T.kind!==k.kind)throw new A("EVIDENCE_KIND_MISMATCH","证据种类与等待项不一致");if(!k.ref.trim()||/^(?:[a-zA-Z]:|[\\/~])/u.test(k.ref)||k.ref.split(/[\\/]/u).includes("..")||!/^[a-f0-9]{64}$/u.test(k.contentHash)||!k.submissionId.trim())throw new A("INVALID_EVIDENCE","证据引用、摘要或提交标识无效");let O=j.steps[T.stepId];if(!O||O.type!=="await_evidence"||O.kind!==k.kind)throw new A("EVIDENCE_STEP_CHANGED","证据等待项与固定工作流不一致");if(!j.transitions.some(X=>X.from===T.stepId&&X.on==="invalidated"))throw new A("EVIDENCE_INVALIDATION_UNAVAILABLE","当前工作流未声明证据失效后的恢复路径");let J=l.get(mt(O.validator));if(!J)throw new A("EVIDENCE_VALIDATOR_UNAVAILABLE","未注册证据验证器版本");let K=ds(await J.validate({run:Ye(C),kind:k.kind,ref:k.ref,contentHash:k.contentHash,context:gn(k.context)}));if(K.accepted&&K.actualHash===k.contentHash)throw new A("EVIDENCE_STILL_VALID","当前证据仍然有效,不能使其失效");let Y=(K.reason?.trim()||"证据未通过验证或内容已改变").slice(0,4096);T.status="invalidated",T.invalidation={ref:k.ref,contentHash:k.contentHash,submissionId:k.submissionId,reason:Y};let z=v(C,j,{kind:"evidence-invalidated",stepId:T.stepId,evidenceKind:k.kind,ref:k.ref,contentHash:k.contentHash,submissionId:k.submissionId,reason:Y},"invalidated");Fc(C,j,T.stepId,T.sequence,T.results,{ref:k.ref,contentHash:k.contentHash,reason:Y},"invalidated",z),uo(C,j)})}async function S(k){return R(k,C=>{b(C);let j=C.waits.find(T=>T.id===k.waitId);if(!j||j.status!=="pending"||j.proposalHash!==k.proposalHash)throw new A("STALE_PROPOSAL","只能修改当前仍在等待决定的提案");j.proposal=pt(k.proposal),j.proposalHash=D(j.proposal)})}async function P(k){let C=await R(k,j=>{if(j.status==="completed"){if(k.stoppedActions?.length)throw new A("ACTION_TERMINAL","已完成 Run 不接受取消停止确认");return}let T=j.status==="cancelled";if(T||(j.actions=j.actions.map(O=>_m(O,k.reason))),k.stoppedActions!==void 0){if(!Array.isArray(k.stoppedActions))throw new A("INVALID_ACTION","stoppedActions 必须是停止确认数组");let O=new Set;for(let J of k.stoppedActions){if(!J||typeof J!="object"||O.has(J.actionId))throw new A("INVALID_ACTION","停止确认重复或无效");O.add(J.actionId);let K=N(j,J.actionId);j.actions[j.actions.indexOf(K)]=Ok(K,J)}}if(!T){for(let O of j.waits)O.status==="pending"&&(O.status="cancelled");for(let O of j.evidenceWaits??[])O.status==="pending"&&(O.status="cancelled");j.ready=[],j.status="cancelled",j.reason=k.reason}});return C.status==="cancelled"&&await G(C),C}async function B(k){return R(k,C=>{if(!Array.isArray(k.stoppedActions)||!k.stoppedActions.length)throw new A("INVALID_ACTION","stoppedActions 必须是非空停止确认数组");let j=new Set;for(let T of k.stoppedActions){if(!T||typeof T!="object"||j.has(T.actionId))throw new A("INVALID_ACTION","停止确认重复或无效");j.add(T.actionId);let O=N(C,T.actionId);C.actions[C.actions.indexOf(O)]=jk(O,T)}})}async function V(k){return R(k,C=>{b(C);let j=N(C,k.actionId);if(j.attempt!==k.attempt)throw new A("STALE_ACTION","Action 执行尝试已经改变");C.actions[C.actions.indexOf(j)]=Px(j,k.reason)})}async function H(k){return R(k,async(C,j)=>{b(C);let T=N(C,k.actionId);if(T.attempt!==k.attempt)throw new A("STALE_ACTION","Action 执行尝试已经改变");if(T.type==="child_workflow")throw new A("CHILD_MANAGED","子工作流由 Runtime 管理,不支持通过通用 retry 重置父 Action;保留原有子 Run 和执行记录");if(T.status==="succeeded"&&e.validateRecovery){if(k.expectedRevision===void 0)throw new A("REVISION_CONFLICT","恢复已提交结果必须绑定当前 Run 版本");if(k.reconciliation!==void 0)throw new A("OUTCOME_ALREADY_RECORDED","已提交结果不能声明未执行;请使用应用的语义恢复");if(typeof k.proposalHash!="string"||!k.proposalHash.trim())throw new A("INVALID_REQUEST","恢复已提交结果必须绑定当前应用决定");if(C.actions.some(z=>["running","unknown"].includes(z.status)))throw new A("ACTION_IN_FLIGHT","已有 Action 的执行结果不明,不能恢复");if(C.status!=="completed"||C.ready.length>0||C.actions.some(z=>z.status==="pending")||C.waits.some(z=>z.status==="pending")||C.evidenceWaits?.some(z=>z.status==="pending")||Object.values(C.joins).some(z=>Object.values(z).some(X=>X.length>0))||!T.outcome||T.outcome.status!=="succeeded")throw new A("RUN_TERMINAL","当前 Run 不符合已提交结果的恢复条件");let O=ds(await e.validateRecovery({run:Ye(C),action:Ye(T),outcome:Ye(T.outcome),context:gn(k.context),proposalHash:k.proposalHash}));if(!O.accepted)throw new A("ACTION_TERMINAL",O.reason??"应用拒绝恢复此结果");let J=T.outcome.event??"succeeded",K=v(C,j,{kind:"action-outcome",stepId:T.stepId,outcome:T.outcome},J);if(K?.length===0||K===void 0&&!j.transitions.some(z=>z.from===T.stepId&&z.on===J))throw new A("ACTION_TERMINAL","应用未声明可恢复的后续工作");let Y=C.actionContexts[T.id];Fc(C,j,T.stepId,Y.sequence,Y.results,T.outcome.output,J,K),uo(C,j);return}if(T.status==="failed"){let O=C.actionContexts[T.id].sequence,J=Y=>Object.hasOwn(Y,T.stepId)&&Y[T.stepId].sequence===O;if(Object.values(C.actionContexts).some(Y=>J(Y.results))||C.waits.some(Y=>J(Y.results))||C.evidenceWaits?.some(Y=>J(Y.results))||C.ready.some(Y=>J(Y.results))||Object.values(C.joins).some(Y=>Object.values(Y).some(z=>z.some(X=>J(X.results)))))throw new A("ACTION_ALREADY_ADVANCED","该失败结果已推进工作流,不能重新执行旧 Action")}C.actions[C.actions.indexOf(T)]=Tx(T,k.reconciliation),C.status="running",delete C.reason})}async function U(k,C){let j=s.get(k.executorId);if(!j)throw new A("EXECUTOR_UNAVAILABLE","未注册指定的执行器");let T=C??await y(k.runId),O=N(T,k.actionId);if(O.status!=="pending")throw new A("ACTION_ALREADY_CLAIMED","不能重复执行已派发的 Action;请先查询和核对结果");if(!WA(j,O))throw new A("EXECUTOR_UNSUPPORTED","执行器不支持此 Action");Pi(k.context);let J=await nt({...k,attempt:O.attempt,inputHash:O.inputHash,claimToken:DA(),capabilities:j.capabilities},!1,T),K=N(J,k.actionId),Y;try{Pi(k.context),Y=await j.execute(Ye(K),gn(k.context),j.includeRun===!1?void 0:Ye(J))}catch(X){let ce=await y(k.runId),L=N(ce,K.id);throw ce.status!=="cancelled"&&L.status==="running"&&L.attempt===K.attempt&&await V({runId:k.runId,actionId:K.id,attempt:K.attempt,reason:X instanceof Error?X.message:String(X)}),new A("EXECUTION_UNKNOWN","执行器未返回可提交的结果;已保留执行归属,请核对外部操作后恢复")}let z=`${K.id}:${K.attempt}:executor-result`;try{return await q({runId:k.runId,context:gn(k.context),outcome:{...Y,actionId:K.id,attempt:K.attempt,inputHash:K.inputHash,claimToken:K.claim.token,outcomeId:z}},!1,J)}catch(X){let ce=await y(k.runId),L=N(ce,K.id);if(L.receipts.some(ge=>ge.outcomeId===z)){if(L.rejectedOutcomes?.some(ge=>ge.outcome.outcomeId===z))throw X;if(L.outcome?.outcomeId===z)return ce}throw ce.status!=="cancelled"&&L.status==="running"&&L.attempt===K.attempt&&await V({runId:k.runId,actionId:K.id,attempt:K.attempt,reason:X instanceof Error?X.message.slice(0,4096):"执行结果无法提交"}),new A("EXECUTION_UNKNOWN","执行器已返回结果但未能提交;已保留执行归属,请核对外部操作后恢复")}}async function se(k){let C=k.maxActions??100;if(!Number.isSafeInteger(C)||C<1)throw new A("INVALID_REQUEST","maxActions 必须是正安全整数");let j=s.get(k.executorId);if(!j)throw new A("EXECUTOR_UNAVAILABLE","未注册指定的执行器");let T=0,O=await y(k.runId),J=Y=>({reason:Y,run:O,actionsExecuted:T}),K=Y=>{if(O.status==="completed"||O.status==="failed"||O.status==="cancelled")return O.status;if(O.actions.some(z=>z.status==="unknown"&&(!Y||z.type!=="child_workflow")))return"execution-unknown";if(O.actions.some(z=>z.status==="running"&&(!Y||z.type!=="child_workflow")))return"action-in-flight";if(O.waits.some(z=>z.status==="pending"))return"approval-required";if(O.evidenceWaits?.some(z=>z.status==="pending"))return"evidence-required"};for(;;){Pi(k.context);let Y=K(!0);if(Y)return J(Y);(O.ready.length||O.children.length)&&(O=await re({runId:k.runId,context:k.context}));let z=K(!1);if(z)return J(z);let X=O.actions.find(ce=>ce.status==="pending");if(!X)return J("idle");if(T>=C)return J("action-limit");if(!WA(j,X)||X.requiredCapabilities.some(ce=>!j.capabilities.includes(ce)))return J("executor-required");T++;try{O=await U({...k,actionId:X.id},O)}catch(ce){if(!(ce instanceof A)||ce.code!=="EXECUTION_UNKNOWN"||(O=await y(k.runId),!O.actions.some(L=>L.status==="unknown")))throw ce;return J("execution-unknown")}}}async function ee(k){let C=await Ya(e.store,k);return w(C.run,ei),C}async function fe(k){return Wk(await ee(k.runId),k)}function de(k){return async(...C)=>{let j=C.map(T=>BA(T));return Ye(await k(...j))}}return{start:de(W),dispatchCommand:de(F),inspect:de(y),inspectProjection:ee,query:de(fe),inspectCurrent:async k=>await fe({runId:k,view:"current"}),executeCurrent:async k=>QO(await U(BA(k))),runUntilBlockedCurrent:async k=>{let C=await se(BA(k));return{...C,run:QO(C.run)}},next:de(re),claim:de(rr),recordOutcome:de(ne),resolveWait:de(he),recordEvidence:de(Ot),invalidateEvidence:de(_),reviseWait:de(S),cancel:de(P),acknowledgeStopped:de(B),markUnknown:de(V),retry:de(H),execute:de(k=>U(k)),runUntilBlocked:de(se)}}var JO,zO=x(()=>{"use strict";qk();Ga();Ka();_n();xr();TA();Xu();$A();HO();JO=new WeakMap});var KO=x(()=>{"use strict";_n();xr()});import{createRequire as nY}from"node:module";function Sh(e,t){if(!Nh){let r=process.emitWarning;process.emitWarning=((n,...i)=>{String(n instanceof Error?n.message:n).startsWith("SQLite is an experimental feature and might change at any time")||Reflect.apply(r,process,[n,...i])});try{Nh=iY("node:sqlite").DatabaseSync}finally{process.emitWarning=r}}return t===void 0?new Nh(e):new Nh(e,t)}var iY,Nh,VA=x(()=>{"use strict";iY=nY(import.meta.url??__filename)});import{AsyncLocalStorage as oY}from"node:async_hooks";function YO(e){return Math.max(0,Math.min(e,(GO.getStore()?.deadline??1/0)-performance.now()))}function XO(){let e=GO.getStore();if(e&&(e.signal.aborted||performance.now()>=e.deadline))throw new MA}var GO,MA,ZO=x(()=>{"use strict";GO=new oY,MA=class extends Error{code="OPERATION_BUDGET_EXCEEDED";constructor(){super("Operation time budget exceeded; unfinished work can be resumed.")}}});import{randomUUID as aY}from"node:crypto";import{promises as ua}from"node:fs";import Pd from"node:path";import{performance as ej}from"node:perf_hooks";async function tj(e){let t,r;try{let n=await ua.lstat(e);if(!n.isFile()||n.isSymbolicLink())throw new Error("File lock metadata must be a regular file: "+e);r=[n.dev,n.ino,n.size,n.mtimeMs].join(":"),t=await ua.readFile(e,"utf8")}catch(n){if(n.code==="ENOENT")return null;throw n}try{let n=JSON.parse(t),i=n.nonce??n.id,o=typeof n.createdAt=="number"?n.createdAt:Date.parse(n.createdAt);if(typeof i=="string"&&i&&Number.isFinite(o))return{owner:{nonce:i,createdAt:o,...n.protocolVersion===2?{protocolVersion:2}:{},...typeof n.operation=="string"?{operation:n.operation}:{}},token:i,legacy:n.protocolVersion!==2}}catch{}return{owner:null,token:r,legacy:!0}}async function sY(e){let t=e+".sqlite";try{let n=await ua.lstat(t);if(!n.isFile()||n.isSymbolicLink())throw new Error("File lock database must be a regular file: "+t)}catch(n){if(n.code!=="ENOENT")throw n}let r;try{r=Sh(Pd.toNamespacedPath(t))}catch(n){throw new Error("Unable to open Runtime lock database "+t,{cause:n})}try{return r.exec("PRAGMA busy_timeout=0; BEGIN IMMEDIATE;"),r}catch(n){if(r.close(),/database is (?:locked|busy)/iu.test(String(n)))return null;throw new Error("Unable to acquire Runtime lock transaction "+t,{cause:n})}}function rj(e){try{e.exec("ROLLBACK;")}finally{e.close()}}async function cY(e,t={}){e=Pd.resolve(e),await ua.mkdir(Pd.dirname(e),{recursive:!0});let r=await ua.lstat(Pd.dirname(e));if(!r.isDirectory()||r.isSymbolicLink())throw new Error("File lock parent must be a real directory: "+Pd.dirname(e));let n=ej.now()+YO(t.timeoutMs??3e4),i;for(;XO(),i=await sY(e),!i;){if(ej.now()>=n)throw new Error("Timed out waiting for file lock: "+e);await new Promise(s=>setTimeout(s,t.retryMs??20))}let o={protocolVersion:2,nonce:aY(),createdAt:Date.now(),...t.operation?{operation:t.operation}:{}};try{let s=await tj(e);if(s?.legacy)throw new Error("Legacy lock requires confirmation that its previous operation stopped: "+e+`
|
|
195
|
+
Inspect argv: `+JSON.stringify(["comet","doctor","--lock-file",e,"--json"]));s&&await ua.unlink(e),await ua.writeFile(e,JSON.stringify(o),{mode:384,flag:"wx"})}catch(s){throw rj(i),s}let a=!1;return{owner:o,async release(){if(a)return!0;a=!0;let s=!0;try{let c=await tj(e);c?.token===o.nonce?c.owner?.createdAt===o.createdAt&&c.owner.operation===o.operation?await ua.unlink(e):(s=!1,process.stderr.write("[comet] lock metadata changed while held; kept "+e+`
|
|
196
|
+
`)):c&&(s=!1,process.stderr.write("[comet] lock owned by another holder; kept "+e+`
|
|
197
|
+
`))}finally{rj(i)}return s}}}async function nj(e,t,r={}){let n=await cY(e,r),i;try{i=await t()}catch(o){try{await n.release()}catch(a){process.stderr.write("[comet] lock cleanup failed; preserved the original operation error: "+String(a)+`
|
|
198
|
+
`)}throw o}return await n.release(),i}var ij=x(()=>{"use strict";VA();ZO()});function aj(e){return Eh(e).encoded}function Eh(e){let t=new WeakMap,r=new Map,n=u=>{if(typeof u=="string"){let m=r.get(u);return m===void 0&&(m=JSON.stringify(u).length,r.set(u,m)),m}if(u===null||typeof u!="object")return JSON.stringify(u).length;let f=oj.get(u)??t.get(u);if(f!==void 0)return f;let d=Object.entries(u),p=2+Math.max(0,d.length-1)+d.reduce((m,[h,g])=>m+(Array.isArray(u)?0:n(h)+1)+n(g),0);return t.set(u,p),In(u)&&oj.set(u,p),p},i=n(e),o=()=>({encoded:{record:e},json:`{"record":${JSON.stringify(e)}}`});if(i<128*1024)return o();let a=[],s=(u,f)=>{if(!u||typeof u!="object")return;let d=u;if(!(d.protocolVersion!==1||!Array.isArray(d.actions)||!d.actionContexts)){for(let[p,m]of d.actions.entries())m.input&&typeof m.input=="object"&&Object.hasOwn(m.input,"outputs")&&a.push({path:[...f,"actions",String(p),"input","outputs"],group:"outputs"});for(let[p,m]of Object.entries(d.actionContexts))m?.results&&a.push({path:[...f,"actionContexts",p,"results"],group:"results"});d.outputs&&a.push({path:[...f,"outputs"],group:"results"});for(let p of["ready","waits","evidenceWaits"])for(let[m,h]of(d[p]??[]).entries())h.results&&a.push({path:[...f,p,String(m),"results"],group:"results"})}};if(s(e,[]),s(e.run,["run"]),!a.length)return o();let c=Lx(e,a,In),l=JSON.stringify(c);return l.length<i*.9?{encoded:c,json:l}:o()}var oj,FA=x(()=>{"use strict";Ga();xr();oj=new WeakMap});import{createHash as cj,randomUUID as Zie}from"node:crypto";import{types as lY}from"node:util";import{promises as Wn}from"node:fs";import Lt from"node:path";function ps(e){if(typeof e!="string"||e.trim().length===0)throw new A("STORE_INVALID_RUN_ID","runId 必须是非空字符串")}function uY(e){return ps(e),cj("sha256").update(JSON.stringify(e)).digest("hex")}function Ch(e){if(!Number.isSafeInteger(e)||e<1)throw new A("STORE_INVALID_REVISION","revision 必须是正安全整数")}function dY(e,t,r,n=!0){if(ps(e),lY.isProxy(r))throw new A("STORE_INVALID_RUN_ID","RuntimeStore records must be plain JSON data");t!==null&&Ch(t),xn(r);let i=n?structuredClone(r):r;if(!i||typeof i!="object"||Array.isArray(i)||i.runId!==e)throw new A("STORE_INVALID_RUN_ID","next.runId 必须与目标 runId 一致");if(Ch(i.revision),i.revision!==(t??0)+1)throw new A("STORE_INVALID_REVISION","next.revision 必须比预期 revision 增加 1");return i}function fY(e,t,r){let n=pt(r);if(ps(e),!n||n.runId!==e)throw new A("STORE_INVALID_RUN_ID","checkpoint.runId 必须与目标 runId 一致");if(Ch(n.revision),t!==null&&t!==1||n.revision<=(t??0))throw new A("STORE_INVALID_REVISION","恢复仅允许缺失 Run 或相同的初始导入,且不能回退 revision");return JSON.stringify(n)}function lj(e,t,r){let n=pt(e);n.revision=t;for(let i of r){let o=n;for(let a of i.slice(0,-1))o=o[a];o[i.at(-1)]=t}return n}function pY(e,t,r,n=[]){return(e?.revision??null)===t&&(e===null||Ei(e)===Ei(lj(r,1,n)))}function ht(e){if(typeof e.rootDir!="string"||e.rootDir.trim().length===0)throw new A("STORE_INVALID_ROOT","rootDir 必须是非空路径");let t=(e.mirroredRevisionPaths??[]).map(_=>{if(_!=="run.revision")throw new A("STORE_INVALID_REVISION","仅支持 run.revision 镜像字段");return["run","revision"]});function r(_){for(let S of t){let P=_;for(let B of S){if(!P||typeof P!="object"||Array.isArray(P)||!Object.hasOwn(P,B))throw new A("STORE_CORRUPT_RECORD","镜像 revision 字段缺失");P=P[B]}if(P!==_.revision)throw new A("STORE_CORRUPT_RECORD","镜像 revision 与记录版本不一致")}}let n=Lt.resolve(e.rootDir),i=Lt.parse(n).root,o=Lt.relative(i,n).replaceAll("\\","/");if(!o)throw new A("STORE_INVALID_ROOT","rootDir 不能是文件系统根目录");let a={label:"RuntimeStore root",expected:"directory"},s=uY,c="checkpoint.json",l="comet.runtime-store-format.v2",u=".runtime-store-v2",f=_=>`${u}/${s(_)}`,d=_=>`.runtime-store-history/${s(_)}`,p="comet.runtime-store-format.v3",m="comet.runtime-store-snapshot.v2",h=".write.lock",g=/^[0-9]{16}\.json$/u;function v(){return{record:null,compacted:!1,legacyRevision:null,formatPresent:!1}}async function w(_,S){let P=await Qe(n,_?`${_}/${S}`:S,Number.MAX_SAFE_INTEGER,{label:"RuntimeStore record"});try{let B=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(P.bytes));return xn(B),B}catch{throw new A("STORE_CORRUPT_RECORD","版本文件不是有效的 UTF-8 JSON 数据")}}function y(_,S,P){if(!_||typeof _!="object"||Array.isArray(_)||_.runId!==S||_.revision!==P||!Number.isSafeInteger(P)||P<1)throw new A("STORE_CORRUPT_RECORD","版本文件的 runId 或 revision 与目标不一致");r(_)}async function R(_,S=!1,P=s(_),B=!0){if(ps(_),!(await ie(i,o,a)).exists)return v();let V=await ie(n,P,{label:"RuntimeStore run",expected:"directory"});if(!V.exists)return v();let H=await Wn.lstat(V.target),U=await Wn.readdir(V.target,{withFileTypes:!0}),se=await Wn.lstat(V.target);if(await ie(i,`${o}/${P}`,a),!H.isDirectory()||H.isSymbolicLink()||!se.isDirectory()||se.isSymbolicLink()||!ot({dev:H.dev,ino:H.ino,birthtime:H.birthtimeMs},{dev:se.dev,ino:se.ino,birthtime:se.birthtimeMs}))throw new A("STORE_CHANGED_DIRECTORY","读取版本列表时 Run 目录已变化");let ee=new Set,fe=[],de=0;for(let L of U){if((L.name===`${h}.contenders`||L.name==="legacy"&&P===f(_))&&L.isDirectory()&&!L.isSymbolicLink())continue;if(!L.isFile()||L.isSymbolicLink())throw new A("STORE_INVALID_ENTRY",`版本文件无效:${L.name}`);if(/^\..+\.tmp$/u.test(L.name)||L.name===h||[h+".sqlite",h+".sqlite-journal",h+".sqlite-wal",h+".sqlite-shm"].includes(L.name)||/^\.write\.lock\.[a-f0-9-]+\.removed$/u.test(L.name)||(ee.add(L.name),L.name===c))continue;if(!g.test(L.name))throw new A("STORE_INVALID_ENTRY",`版本文件无效:${L.name}`);let ge=Number(L.name.slice(0,-5));if(!Number.isSafeInteger(ge)||ge<1)throw new A("STORE_INVALID_ENTRY",`版本文件无效:${L.name}`);fe.push(L.name),de=Math.max(de,ge)}let k=!1;if([f(_),d(_)].includes(P)&&fe.length>0)throw new A("STORE_INVALID_ENTRY","checkpoint 目录不能包含旧版本文件");if(ee.has(c)){if(![f(_),d(_)].includes(P))throw new A("STORE_INVALID_ENTRY","旧版本目录包含未知 checkpoint");let L=await w(P,c),ge=L?.record,oe=L?.legacyRevision;if(!L||![m,"comet.runtime-store-snapshot.v3"].includes(String(L.schema))||!ge||Object.keys(L).some(vt=>!["schema","record","hash","legacyRevision",...L.schema==="comet.runtime-store-snapshot.v3"?["pool"]:[]].includes(vt))||oe!==null&&(!Number.isSafeInteger(oe)||oe<1||oe>ge.revision)||L.hash!==D({record:ge,legacyRevision:oe,...L.schema==="comet.runtime-store-snapshot.v3"?{pool:L.pool}:{}}))throw new A("STORE_CORRUPT_RECORD","RuntimeStore checkpoint 损坏或校验值不一致");let Re;try{Re=L.schema==="comet.runtime-store-snapshot.v3"?Om(ge,L.pool,B):ge}catch(vt){throw new A("STORE_CORRUPT_RECORD",`RuntimeStore history references are invalid: ${vt instanceof Error?vt.message:String(vt)}`)}return y(Re,_,Re.revision),{record:Re,compacted:!0,legacyRevision:oe,formatPresent:k}}if(!de)return v();let C=new Map,j=L=>`${String(L).padStart(16,"0")}.json`,T=L=>ee.has(j(L));async function O(L){if(C.has(L))return C.get(L);let ge=await w(P,j(L));return(L<=2||L===de)&&C.set(L,ge),ge}async function J(L,ge=0,oe=de){if(y(L,_,oe),S)for(let Re of fe){let vt=Number(Re.slice(0,-5));vt!==ge&&y(await O(vt),_,vt)}return{record:L,compacted:!1,legacyRevision:L.revision,formatPresent:!1}}let K=await O(de);if(de===fe.length&&(K?.schema!==sj||K?.runId!==void 0))return J(K);if(!T(1))throw new A("STORE_MISSING_REVISION","版本历史缺少 revision 1");let Y=null;for(let L of[1,2]){if(!T(L))break;let ge=await O(L);if(ge?.schema!==sj||"runId"in ge)continue;let oe=ge.record;if(oe&&r(oe),!oe||oe.runId!==_||!Number.isSafeInteger(oe.revision)||oe.revision<L||ge.hash!==D(oe)||Object.keys(ge).some(Re=>!["schema","record","hash"].includes(Re))||L===2&&Ei(await O(1))!==Ei(lj(oe,1,t)))throw new A("STORE_CORRUPT_RECORD","恢复 checkpoint 与版本基线不一致");Y={slot:L,record:oe};break}let z=Y?.record.revision??0,X=Y?.slot??0,ce=de===X?z:de;if(ce<z||fe.length!==ce-z+X||fe.some(L=>{let ge=Number(L.slice(0,-5));return ge>X&&ge<=z})){let L=z+1;for(;T(L);)L+=1;throw new A("STORE_MISSING_REVISION",`版本历史缺少 revision ${L}`)}return J(Y&&de===Y.slot?Y.record:K,X,Y&&de===Y.slot?Y.record.revision:de)}async function N(_){let S=await ie(n,s(_),{label:"RuntimeStore format",expected:"any"}),P=await ie(n,`${f(_)}/legacy`,{label:"RuntimeStore legacy",expected:"directory"});if(S.kind==="directory"&&P.exists&&(S=await ie(n,s(_),{label:"RuntimeStore format",expected:"any"})),S.kind==="directory"&&P.exists)throw new A("STORE_MIGRATION_CONFLICT","旧写入者在迁移期间重新创建了 Run 目录;请停止旧版本进程并检查两处版本历史");let B=null;if(S.kind==="file"){let V=await w("",s(_));if(!V||V.runId!==_||(V.schema===l?!["pending","ready"].includes(V.state)||Object.keys(V).some(H=>!["schema","runId","state","writerProtocol"].includes(H)):V.schema!==p||!["closing","closed","reopening"].includes(V.state)||!Number.isSafeInteger(V.revision)||V.revision<1||typeof V.recordHash!="string"||!/^[a-f0-9]{64}$/u.test(V.recordHash)||Object.keys(V).some(H=>!["schema","runId","state","revision","recordHash","writerProtocol"].includes(H))))throw new A("STORE_CORRUPT_RECORD","RuntimeStore 格式标记损坏");if(V.writerProtocol!==void 0&&V.writerProtocol!=="application-holder-v1")throw new A("STORE_WRITER_FENCED","存储协议版本不受支持");B=V}return{original:S,staged:P,marker:B}}function b(_){return Gu(_)?ei(_,{cachePrefixes:!1}):D(_)}async function E(_,S){let P=await R(_,!1,f(_),!1),B=await R(_,!1,d(_),!1);if(!P.record&&!B.record||S.state==="closed"&&(P.record||!B.record))throw new A("STORE_HISTORY_CONFLICT","历史事务与 checkpoint 位置不一致");if(P.record&&B.record){let H=await Wn.lstat(Lt.join(n,f(_),c)),U=await Wn.lstat(Lt.join(n,d(_),c)),se={dev:H.dev,ino:H.ino,birthtime:H.birthtimeMs},ee={dev:U.dev,ino:U.ino,birthtime:U.birthtimeMs};if(!_u(se,ee)||!ot(se,ee))throw new A("STORE_HISTORY_CONFLICT","活动与历史分区含两份独立 checkpoint,已保留现场")}let V=B.record??P.record;if(V.revision!==S.revision||b(V)!==S.recordHash||P.record&&P.record!==V&&b(P.record)!==S.recordHash)throw new A("STORE_HISTORY_CONFLICT","历史事务的固定版本与 checkpoint 不一致");return{record:V,active:!!P.record,history:!!B.record}}async function I(_){if(ps(_),!(await ie(i,o,a)).exists)return"missing";let S=await N(_),P=await ie(n,`${f(_)}/${c}`,{label:"RuntimeStore 活动 checkpoint",expected:"file"}),B=await ie(n,`${d(_)}/${c}`,{label:"RuntimeStore 历史 checkpoint",expected:"file"});if(S.marker?.schema===p){if(!P.exists&&!B.exists||S.marker.state==="closed"&&(P.exists||!B.exists))throw new A("STORE_HISTORY_CONFLICT","历史分区与存储事务不一致");return S.marker.state}if(B.exists)throw new A("STORE_HISTORY_CONFLICT","历史分区缺少存储事务");return S.marker||P.exists||S.original.kind==="directory"||S.staged.exists?"active":"missing"}async function W(_,S,P){await Dt(Lt.join(n,s(_)),JSON.stringify({schema:p,...e.writerProtocol?{writerProtocol:e.writerProtocol}:{},runId:_,state:S,revision:P.revision,recordHash:b(P)})+`
|
|
199
|
+
`,{containedRoot:n,requireAtomicPublication:!0})}async function F(_){let S=(await N(_)).marker;if(!S||!["closing","reopening"].includes(S.state))return;let P=S.state==="closing",B=(await E(_,S)).record,V=await E(_,S),H=P?f(_):d(_),U=P?d(_):f(_);await $t(n,U,{label:"RuntimeStore 历史目标"});let se=Lt.join(n,H,c),ee=Lt.join(n,U,c),fe=P?V.active:V.history;(P?V.history:V.active)||(await ie(n,`${H}/${c}`,{label:"RuntimeStore 历史源",expected:"file"}),await ie(n,U,{label:"RuntimeStore 历史目标",expected:"directory"}),await Wn.link(se,ee),await E(_,S)),await nt(Lt.dirname(ee)),await nt(Lt.dirname(Lt.dirname(ee))),await nt(n),fe&&(await E(_,S),await Fa(se,{containedRoot:n,beforeRemove:async()=>{await E(_,S)}}),await nt(Lt.dirname(se))),P?await W(_,"closed",B):await re(_,"ready",!1);let k=await Z(_,!1);if(!k||k.revision!==B.revision||b(k)!==b(B))throw new A("STORE_HISTORY_CONFLICT","历史转换提交后固定版本发生变化")}async function G(_,S,P){return ps(_),Ch(S),rr(_,async()=>{await F(_);let B=(await N(_)).marker,V;if(B?.schema===p){if(P&&B.state==="reopening")throw new A("STORE_HISTORY_CONFLICT","请先完成正在进行的恢复事务");if(!P&&B.state==="closing")throw new A("STORE_HISTORY_CONFLICT","请先完成正在进行的封存事务");if(V=(await E(_,B)).record,V.revision!==S)return!1;if(P&&B.state==="closed")return!0}else{if(V=(await he(_,!1)).record,!V||V.revision!==S)return!1;if(!P)return!0}return await W(_,P?"closing":"reopening",V),await F(_),!0})}async function Z(_,S=!0){if(ps(_),!(await ie(i,o,a)).exists)return null;let P=await N(_);if(P.marker?.schema===p){let{record:H}=await E(_,P.marker);return S?Pr(H):H}if((await R(_,!1,d(_),!1)).record)throw new A("STORE_HISTORY_CONFLICT","历史 checkpoint 缺少对应存储事务");let V=await R(_,!1,f(_),S);if(V.record){if(!P.marker&&!(await N(_)).marker)throw new A("STORE_CORRUPT_RECORD","RuntimeStore 格式标记缺失");return V.record}if(P.original.kind==="directory"){let H=(await R(_)).record;if(!H&&(await N(_)).original.kind!=="directory")throw new A("STORE_CHANGED_LAYOUT","读取期间旧 Run 已迁移");return H}if(P.marker?.state==="ready")throw new A("STORE_CORRUPT_RECORD","RuntimeStore checkpoint 缺失,不能回退到旧版本");if(P.staged.exists){let H;try{H=(await R(_,!1,`${f(_)}/legacy`)).record}catch(U){throw(await N(_)).marker?.state==="ready"?new A("STORE_CHANGED_LAYOUT","读取期间旧 Run 已压缩"):U}if(!H){let U=await N(_);if(!U.staged.exists||U.marker?.state==="ready")throw new A("STORE_CHANGED_LAYOUT","读取期间旧 Run 已压缩")}return H}return null}async function Ae(_,S=!0){for(let P=0;;P+=1)try{return await Z(_,S)}catch(B){let V=B instanceof ir&&B.reason==="changed",H=["ENOENT","ENOTDIR"].includes(B.code??""),U=B instanceof Error&&/must be a real directory|STORE_CHANGED_DIRECTORY|STORE_CHANGED_LAYOUT/u.test(B.message);if(!V&&!H&&!U||P>=15)throw B}}async function re(_,S,P){await Dt(Lt.join(n,s(_)),JSON.stringify({schema:l,...e.writerProtocol?{writerProtocol:e.writerProtocol}:{},runId:_,state:S})+`
|
|
200
|
+
`,{containedRoot:n,exclusive:P,requireAtomicPublication:!0})}async function nt(_){let S;try{S=await Wn.open(_,"r"),await S.sync()}catch(P){if(!["EACCES","EBADF","EINVAL","EISDIR","ENOTSUP","EPERM"].includes(P.code??""))throw P}finally{await S?.close()}}async function rr(_,S){if(await $t(i,o,a),(await ie(n,".runtime-store-coordination",{label:"RuntimeStore 写入协议",expected:"directory"})).exists&&e.writerProtocol!=="application-holder-v1")throw new A("STORE_WRITER_FENCED","此 Store 已启用应用协调协议,请使用应用写入入口");await $t(n,f(_),{label:"RuntimeStore run"}),await nt(Lt.join(n,u)),await nt(n);try{return e.singleWriter?await S():await nj(Lt.join(n,f(_),h),S)}catch(B){throw["ENOTSUP","EOPNOTSUPP"].includes(B.code??"")?new A("STORE_ATOMIC_PUBLICATION_UNSUPPORTED","此文件系统不支持原子硬链接发布;请使用支持硬链接的本地目录或其他 RuntimeStore"):B}}async function q(_,S,P,B=Eh(S)){let V=Lt.join(n,f(_)),H=P.legacyRevision,{encoded:U,json:se}=B,ee=U.pool?{record:U.record,legacyRevision:H,pool:U.pool}:{record:S,legacyRevision:H},fe=U.pool?"comet.runtime-store-snapshot.v3":m,de=`{"schema":${JSON.stringify(fe)},${se.slice(1,-1)},"legacyRevision":${JSON.stringify(H)},"hash":${JSON.stringify(D(ee))}}
|
|
201
|
+
`;await Dt(Lt.join(V,c),de,{containedRoot:n,exclusive:!P.compacted,requireAtomicPublication:!0}),P.formatPresent||await re(_,"ready",!1)}async function ne(_,S){if(S===null)return;let P=`${f(_)}/legacy`,B=await ie(n,P,{label:"RuntimeStore legacy",expected:"directory"});if(B.exists)try{for(let V of await Wn.readdir(B.target,{withFileTypes:!0}))V.isFile()&&!V.isSymbolicLink()&&g.test(V.name)&&Number(V.name.slice(0,-5))<=S&&await Fa(Lt.join(B.target,V.name),{containedRoot:n});await ie(n,P,{label:"RuntimeStore legacy",expected:"directory"}),await Wn.rmdir(B.target).catch(V=>{if(V.code!=="ENOTEMPTY"&&V.code!=="EEXIST")throw V})}catch(V){process.stderr.write(`[comet] warning: RuntimeStore checkpoint 已提交,旧版本清理将在下次写入重试:${V instanceof Error?V.message:String(V)}
|
|
202
|
+
`)}}async function he(_,S=!0){let P=(await N(_)).marker;if(P?.writerProtocol&&P.writerProtocol!==e.writerProtocol)throw new A("STORE_WRITER_FENCED","此 Run 需要应用协调写入协议");await F(_);let B=await N(_);if(B.marker?.schema===p)throw new A("STORE_RUN_CLOSED","Run 已封存或正在转换历史分区;请显式恢复后再写入");if((await R(_,!1,d(_),!1)).record)throw new A("STORE_HISTORY_CONFLICT","历史 checkpoint 缺少对应存储事务");let H=await R(_,!1,f(_),S);if(H.record&&!B.marker)throw new A("STORE_CORRUPT_RECORD","RuntimeStore 格式标记缺失,不能恢复旧写入路径");if(B.original.kind==="directory"){await R(_,!0);let se=await Wn.lstat(B.original.target);await ie(i,`${o}/${s(_)}`,a),await ie(n,f(_),a),await Wn.rename(B.original.target,B.staged.target);let ee=await Wn.lstat(B.staged.target);if(!ee.isDirectory()||ee.isSymbolicLink()||!ot({dev:se.dev,ino:se.ino,birthtime:se.birthtimeMs},{dev:ee.dev,ino:ee.ino,birthtime:ee.birthtimeMs}))throw new A("STORE_CHANGED_DIRECTORY","迁移时旧 Run 目录已变化");await nt(Lt.join(n,f(_))),await nt(n),B=await N(_)}if(!B.marker){try{await re(_,"pending",!0)}catch(se){throw["EEXIST","EISDIR","ENOTDIR"].includes(se.code??"")?new A("STORE_MIGRATION_CONFLICT","旧写入者在迁移期间重新创建了 Run 路径;已保留迁移现场,未提交新 checkpoint"):se}B=await N(_)}let U=H;if(!U.record&&B.marker?.state==="ready")throw new A("STORE_CORRUPT_RECORD","RuntimeStore checkpoint 缺失,不能回退到旧版本");return!U.record&&B.staged.exists?(U=await R(_,!0,`${f(_)}/legacy`),U.record&&(await q(_,U.record,U),U={...U,compacted:!0,formatPresent:!0})):U.record&&B.marker?.state==="pending"&&await re(_,"ready",!1),U.record&&(U.formatPresent=!0,await ne(_,U.legacyRevision)),U}return{queryScope:`file:${cj("sha256").update(n).digest("hex")}`,read:Ae,readProjection:_=>Ae(_,!1),readPartitionMetadata:I,settleRun:_=>Ri(async()=>await I(_)==="missing"?"missing":rr(_,async()=>{await F(_);let S=(await N(_)).marker;return S&&e.writerProtocol&&S.writerProtocol!==e.writerProtocol&&await Dt(Lt.join(n,s(_)),JSON.stringify({...S,writerProtocol:e.writerProtocol})+`
|
|
203
|
+
`,{containedRoot:n,requireAtomicPublication:!0}),I(_)})),closeRun:(_,S)=>Ri(()=>G(_,S,!0)),reopenRun:(_,S)=>Ri(()=>G(_,S,!1)),async readDisposition(_){if(!await Ae(_,!1))return"missing";let P=(await N(_)).marker;return P?.schema===p?P.state:"active"},async restoreCheckpoint(_,S,P){let B=JSON.parse(fY(_,S,P));return r(B),rr(_,async()=>{let V=await he(_);return pY(V.record,S,B,t)?(await q(_,B,V),!0):!1})},compareAndSwap:async(_,S,P)=>Ot(_,S,P)(),prepareCompareAndSwap:Ot};function Ot(_,S,P){dY(_,S,P,!1),r(P);let{json:B}=Eh(P),V=JSON.parse(B);return()=>rr(_,async()=>{let H=await he(_,!1);return(H.record?.revision??null)!==S?!1:(await q(_,V.record,H,{encoded:V,json:B}),!0)})}}var sj,HA=x(()=>{"use strict";mc();Xo();ij();Yn();lt();xr();Ni();_n();FA();Ga();sj="comet.runtime-store-checkpoint.v1"});import{createHash as uj}from"node:crypto";import{promises as fo}from"node:fs";import da from"node:path";async function QA(e){let t=da.resolve(e.rootDir),r=da.parse(t).root,n=da.relative(r,t).replaceAll("\\","/");if(!n)throw new A("STORE_INVALID_ROOT","rootDir 不能是文件系统根目录");if(!(await ie(r,n,{label:"RuntimeStore discovery",expected:"directory"})).exists)return[];let i=[];for(let o of await fo.readdir(t,{withFileTypes:!0}))if(!(/^\.[a-f0-9]{64}\.[a-f0-9-]{36}\.tmp$/u.test(o.name)&&o.isFile()&&!o.isSymbolicLink())&&o.name!==".runtime-store-coordination"){if([".runtime-store-v2",".runtime-store-history"].includes(o.name)){let a=await ie(t,o.name,{label:"RuntimeStore checkpoint directory",expected:"directory"});for(let s of await fo.readdir(a.target))i.push(s);continue}i.push(o.name)}return[...new Set(i)].sort((o,a)=>o.localeCompare(a))}async function mY(e,t,r,n=!1){let i=da.resolve(e.rootDir),o=r?[...new Set(r)].filter(d=>d&&d!=="."&&d!==".."&&!d.includes("/")&&!d.includes("\\")):await QA(e),a=r?new Set(r):null,s=[],c=async d=>{let p=await ie(i,d,{label:"RuntimeStore source",expected:"file"});if(!p.exists)return null;let m=await fo.lstat(p.target);return[d,m.size,m.mtimeMs,m.ctimeMs,m.ino,m.dev]},l=async d=>{let p=await ie(i,d,{label:"RuntimeStore source directory",expected:"directory"});if(!p.exists)return null;let m=await fo.lstat(p.target),h=(await fo.readdir(p.target,{withFileTypes:!0})).map(g=>[g.name,g.isFile(),g.isDirectory(),g.isSymbolicLink()]).sort((g,v)=>String(g[0]).localeCompare(String(v[0])));return[d,m.mtimeMs,m.ctimeMs,m.ino,m.dev,h]},u=async d=>JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode((await Qe(i,d,Number.MAX_SAFE_INTEGER,{label:"RuntimeStore discovery record"})).bytes)),f=n?8:1;for(let d=0;d<o.length;d+=f)await Promise.all(o.slice(d,d+f).map(async p=>{if(a&&!a.has(p))return;let m=await fo.lstat(da.join(i,p)).catch(()=>null),h={name:p,isFile:()=>m?.isFile(),isDirectory:()=>m?.isDirectory(),isSymbolicLink:()=>m?.isSymbolicLink()},g=null,v=!1;try{if(!/^[a-f0-9]{64}$/u.test(h.name)||h.isSymbolicLink())throw new A("STORE_INVALID_ENTRY","RuntimeStore 目录含异常项目");let w;if(h.isFile()){let N=await u(h.name);if(!["comet.runtime-store-format.v2","comet.runtime-store-format.v3"].includes(N.schema))throw new A("STORE_CORRUPT_RECORD","RuntimeStore 格式标记无效");if(w=N.runId,n&&N.schema==="comet.runtime-store-format.v3"&&N.state==="closed"){if(!Number.isSafeInteger(N.revision)||N.revision<1||N.writerProtocol!==void 0&&N.writerProtocol!=="application-holder-v1"||typeof N.recordHash!="string"||!/^[a-f0-9]{64}$/u.test(N.recordHash)||Object.keys(N).some(I=>!["schema","runId","state","revision","recordHash","writerProtocol"].includes(I)))throw new A("STORE_CORRUPT_RECORD","RuntimeStore 历史标记损坏");let b=await ie(i,`.runtime-store-v2/${h.name}/checkpoint.json`,{label:"RuntimeStore 活动 checkpoint",expected:"file"}),E=await ie(i,`.runtime-store-history/${h.name}/checkpoint.json`,{label:"RuntimeStore 历史 checkpoint",expected:"file"});if(b.exists||!E.exists)throw new A("STORE_HISTORY_CONFLICT","历史分区与存储事务不一致");v=!0}}else if(h.isDirectory()){await ie(i,h.name,{label:"RuntimeStore legacy directory",expected:"directory"});let N=(await fo.readdir(da.join(i,h.name))).filter(E=>/^[0-9]{16}\.json$/u.test(E)).sort();if(!N.length)throw new A("STORE_CORRUPT_RECORD","RuntimeStore 旧记录缺少版本");let b=await u(`${h.name}/${N.at(-1)}`);w=b.schema==="comet.runtime-store-checkpoint.v1"?b.record?.runId:b.runId}else throw new A("STORE_INVALID_ENTRY","RuntimeStore 项目类型无效");if(typeof w!="string"||!w.trim()||uj("sha256").update(JSON.stringify(w)).digest("hex")!==h.name)throw new A("STORE_CORRUPT_RECORD","RuntimeStore 记录身份与目录不匹配");if(g=w,v)return;let y=t?h.isFile()?[h.name,`.runtime-store-v2/${h.name}/checkpoint.json`,`.runtime-store-history/${h.name}/checkpoint.json`]:(await fo.readdir(da.join(i,h.name))).filter(N=>/^[0-9]{16}\.json$/u.test(N)).sort().map(N=>`${h.name}/${N}`):[],R=uj("sha256").update(JSON.stringify({files:await Promise.all(y.map(c)),directories:t?await Promise.all((h.isFile()?[`.runtime-store-v2/${h.name}`,`.runtime-store-history/${h.name}`]:[h.name]).map(l)):[]})).digest("hex");s.push({storageKey:h.name,runId:g,fingerprint:R,error:null})}catch(w){s.push({storageKey:h.name,runId:g,fingerprint:JSON.stringify(await fo.lstat(da.join(i,h.name)).then(y=>[y.size,y.mtimeMs,y.ctimeMs,y.ino]).catch(()=>null)),error:{code:w instanceof A?w.code:"STORE_UNREADABLE",message:w instanceof Error?w.message:String(w)}})}}));return s.sort((d,p)=>d.storageKey.localeCompare(p.storageKey))}async function UA(e){return mY(e,!0)}var dj=x(()=>{"use strict";lt();HA();_n()});function _h(e){return hY.test(e)?e:`portable-${D(e)}`}function JA(e){let t=aj(e.run);return t.pool?{...e,schema:"comet.workflow-run-checkpoint.v2",run:t.record,pool:t.pool,storageHash:D(t)}:e}function gY(e){return{...e,revision:1,actions:e.actions.map(t=>{let r=new Set((t.rejectedOutcomes??[]).map(i=>i.outcome.outcomeId)),n={...t,receipts:t.receipts.filter(i=>!r.has(i.outcomeId)).map(i=>({...i}))};if(delete n.rejectedOutcomes,t.claim){let i=_h(t.claim.token);if(n.claim={...t.claim,token:i},t.executionStop&&(n.executionStop={...t.executionStop,claimToken:i}),t.cancellation&&(n.cancellation={...t.cancellation,claimToken:i}),t.outcome){n.outcome={...t.outcome,claimToken:i};let o=n.receipts.find(a=>a.outcomeId===t.outcome.outcomeId);o&&(o.hash=D(n.outcome))}}return t.status==="running"&&(n.status="unknown",n.reason="Portable recovery requires reconciliation of external execution"),n})}}function zA(e){let t=Tn(gY(e),e.runId),r=D(t);return{schema:fj,hash:r,run:t,sourceRevision:e.revision,sourceHash:D({hash:r,sourceRevision:e.revision})}}function wY(e,t,r={},n=!1){if(e===void 0)return null;if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`Portable Run checkpoint for ${t} is invalid`);xn(e);let i=e;if(![fj,"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(s=>!["schema","hash","run","sourceRevision","sourceHash",...i.schema==="comet.workflow-run-checkpoint.v2"?["pool","storageHash"]:[]].includes(s))||i.schema==="comet.workflow-run-checkpoint.v2"&&D({record:i.run,pool:i.pool})!==i.storageHash)throw new Error(`Portable Run checkpoint for ${t} is invalid or changed`);let o=i.schema==="comet.workflow-run-checkpoint.v2"?Om(i.run,i.pool,!n):i.run;if((n?ei:D)(o)!==i.hash)throw new Error(`Portable Run checkpoint for ${t} is invalid or changed`);let a=n?$m(o,t,vY):Tn(o,t);if(i.sourceRevision!==void 0||i.sourceHash!==void 0){if(!Number.isSafeInteger(i.sourceRevision)||i.sourceRevision<1||i.sourceHash!==D({hash:i.hash,sourceRevision:i.sourceRevision}))throw new Error(`Portable Run checkpoint revision for ${t} is invalid or changed`);if(r.preserveSourceRevision)return{...a,revision:i.sourceRevision}}return a}function Ih(e,t,r={}){return wY(e,t,r)}function KA(e){let t=structuredClone(e);for(let r of t.actions)r.claim&&!r.executionOrigin&&(r.executionOrigin={workflow:{...e.workflow}});return t}var po,fj,hY,vY,pj=x(()=>{"use strict";Xu();xr();FA();Ga();po="run_checkpoint",fj="comet.workflow-run-checkpoint.v1",hY=/^portable-[a-f0-9]{64}$/u;vY={hash:ei,visitResults:Pm,validateOrigins:Tm}});var ze=x(()=>{"use strict";zO();KO();$A();HA();dj();Xu();_n();xr();pj();qk()});function ms(e){return/^# comet-execution: managed-run\r?\n/u.test(e)}function hj(e,t){let r=(0,xh.parseDocument)(e,{uniqueKeys:!0});if(r.errors.length>0)throw new Error(`${t} is invalid YAML: ${r.errors[0].message}`);return r.toJS({mapAsMap:!1})}function fa(e,t){let r=e.lastIndexOf(mj);if(e.startsWith(Hc)&&r>=0&&e.endsWith(`
|
|
204
|
+
`)){let n=e.slice(r+mj.length,-1);try{let i=JSON.parse(n);if(JSON.stringify(i)===n){let o=e.slice(0,r+1),a=hj(o,t);if(a&&typeof a=="object"&&!Array.isArray(a)&&!Object.hasOwn(a,po)&&Hc+(0,xh.stringify)(a)===o)return{...a,[po]:i}}}catch{}}return hj(e,t)}var xh,Hc,mj,Qc=x(()=>{"use strict";xh=dr(Ur(),1);ze();Hc=`# comet-execution: managed-run
|
|
205
|
+
`;mj=`
|
|
206
|
+
${po}: `});function Ph(e){let t=e.input;if(!t||typeof t!="object"||typeof t.candidateId!="string"||!t.candidateId||typeof t.identityProvider!="string"||!t.identityProvider||typeof t.builderExecutionRef!="string"||!t.builderExecutionRef||t.verifierExecutionRef!==null&&typeof t.verifierExecutionRef!="string"||!Number.isSafeInteger(t.iteration)||t.iteration<1||!Number.isSafeInteger(t.goalCycle)||t.goalCycle<1||typeof t.registeredAt!="string"||Number.isNaN(Date.parse(t.registeredAt))||e.type!=="handoff"||e.ref!=="native-verifier"||e.stepId!=="native-verifier"||t.verifierExecutionRef!==null&&t.verifierExecutionRef===t.builderExecutionRef||e.claim&&(e.claim.executorId!==t.identityProvider||e.claim.token===t.builderExecutionRef||t.verifierExecutionRef!==null&&e.claim.token!==t.verifierExecutionRef))throw new Error("Native Verifier action binding is invalid");return t}function gj(e,t){let r=Ph(t);return t.runId===e.name&&r.candidateId===e.builder_handoff?.candidate_id&&r.identityProvider===e.builder_handoff.identity_provider&&r.builderExecutionRef===e.builder_handoff.builder_execution_ref&&r.iteration===e.loop.iteration&&r.goalCycle===e.loop.goal_cycle&&t.attempt===e.loop.attempt}function GA(e){return e.claim?.token??Ph(e).verifierExecutionRef}var Td=x(()=>{"use strict";Ka();xr()});function Uc(){return{dropped_entries:0,first_dropped_at:null,last_dropped_at:null,outcome_counts:{pass:0,fail:0,blocked:0,"execution-error":0,recovery:0}}}var hs,Od,Jc=x(()=>{"use strict";hs="comet.native.v4",Od=["multi-session","single-session"]});var eR={};fw(eR,{NativePortableStateVersionConflictError:()=>jd,appendNativePortableHistory:()=>vn,compareAndSwapNativePortableState:()=>kj,createNativePortableState:()=>Gc,parseNativePortableState:()=>M,parseNativeReportedChecks:()=>Ti,readNativePortableState:()=>Jt,writeNativePortableState:()=>$d});import{promises as RY}from"node:fs";function IY(e,t){let r=Zt(e,"Native approved children plan");if(!Array.isArray(r.children))throw new Error("Native approved children plan requires children");let n=r.children.map(i=>{let o={...Zt(i,"Native approved child")};return r.schema==="comet.native.children.v2"&&!r.acceptance_index&&typeof o.summary=="string"?delete o.covers:delete o.summary,o});return om(JSON.stringify({...r,children:n}),t.map(i=>i.id),{acceptanceCatalog:t})}function Zt(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function jr(e,t,r){let n=Object.keys(e).filter(i=>!t.has(i));if(n.length>0)throw new Error(`${r} has unknown field(s): ${n.join(", ")}`)}function bt(e,t,r){if(typeof e!="string"||!r?.empty&&e.length===0)throw new Error(`${t} must be ${r?.empty?"a string":"a non-empty string"}`);return e}function XA(e,t){return e===null?null:bt(e,t)}function wj(e,t){let r=bt(e,t);if(!CY.test(r))throw new Error(`${t} must be a SHA-256 hash`);return r}function zc(e,t){if(typeof e!="boolean")throw new Error(`${t} must be a boolean`);return e}function kt(e,t,r=0){if(!Number.isSafeInteger(e)||e<r)throw new Error(`${t} must be a safe integer greater than or equal to ${r}`);return e}function xY(e,t){return e===null?null:kt(e,t,Number.MIN_SAFE_INTEGER)}function Vt(e,t,r){if(typeof e!="string"||!t.includes(e))throw new Error(`${r} must be one of: ${t.join(", ")}`);return e}function qn(e,t,r){if(!Array.isArray(e))throw new Error(`${t} must be an array`);return e.map((n,i)=>r(n,i))}function jh(e,t){return qn(e,t,(r,n)=>bt(r,`${t}[${n}]`))}function gs(e,t){if(new Set(e).size!==e.length)throw new Error(`${t} must be unique`)}function Kc(e,t){let r=bt(e,t);if(Number.isNaN(Date.parse(r)))throw new Error(`${t} must be an ISO date or timestamp`);return r}function Oh(e,t,r=!1){let n=bt(e,t);if(n.includes("\\")||n.startsWith("/")||/^[A-Za-z]:/u.test(n)||n.split("/").includes("..")||!r&&(n==="."||n.split("/").includes(".")))throw new Error(`${t} must be a portable relative path`);return n}function Ln(e,t){let r=Zt(e,t);return jr(r,new Set(["text","truncated"]),t),{text:bt(r.text,`${t}.text`,{empty:!0}),truncated:zc(r.truncated,`${t}.truncated`)}}function PY(e,t){let r=`Native spec_changes[${t}]`,n=Zt(e,r);jr(n,new Set(["capability","operation","source","delta_source","base_hash"]),r);let i=bt(n.capability,`${r}.capability`);if(!SY.test(i))throw new Error(`${r}.capability is invalid`);let o=Vt(n.operation,["create","modify","remove"],`${r}.operation`),a=n.source===null?null:Oh(n.source,`${r}.source`),s=n.delta_source===void 0?void 0:Oh(n.delta_source,`${r}.delta_source`),c=n.base_hash===void 0?void 0:n.base_hash===null?null:wj(n.base_hash,`${r}.base_hash`);if(o==="remove"&&a!==null)throw new Error(`${r} remove requires source null`);if(o!=="remove"&&a===null)throw new Error(`${r} ${o} requires a source`);if(s!==void 0&&o==="remove")throw new Error(`${r} remove cannot contain delta_source`);return{capability:i,operation:o,source:a,...s===void 0?{}:{delta_source:s},...c===void 0?{}:{base_hash:c}}}function TY(e){let t="Native workspace",r=Zt(e,t);jr(r,new Set(["isolation","change_branch","target_branch","finish"]),t);let n=Vt(r.isolation,["current","branch","worktree"],`${t}.isolation`),i=XA(r.change_branch,`${t}.change_branch`),o=XA(r.target_branch,`${t}.target_branch`),a=r.finish===null?null:Vt(r.finish,["merge","push","pull-request","keep"],`${t}.finish`);if(n==="current"&&a!==null)throw new Error("Native current workspace cannot contain a finish action");if(n==="current"&&i===null!=(o===null))throw new Error("Native workspace branch bindings must both be present or both be null");if(n!=="current"&&(i===null||o===null))throw new Error("Native isolated workspace requires change_branch and target_branch");return{isolation:n,change_branch:i,target_branch:o,finish:a}}function OY(e){let t="Native loop",r=Zt(e,t);jr(r,new Set(["stage","goal_cycle","iteration","attempt","retry_epoch","failed_iteration_count","no_progress_count","stop_reason","execution_failure_count","previous_unresolved_ids","next_action"]),t);let n=jh(r.previous_unresolved_ids,`${t}.previous_unresolved_ids`);gs(n,`${t}.previous_unresolved_ids`);let i=r.stop_reason===void 0?void 0:Vt(r.stop_reason,["budget","stalled"],`${t}.stop_reason`);return{stage:Vt(r.stage,["shape","building","verify-ready","repairing","archive-ready","await-user","blocked","done"],`${t}.stage`),goal_cycle:kt(r.goal_cycle,`${t}.goal_cycle`,1),iteration:kt(r.iteration,`${t}.iteration`),attempt:kt(r.attempt,`${t}.attempt`),retry_epoch:kt(r.retry_epoch,`${t}.retry_epoch`),failed_iteration_count:kt(r.failed_iteration_count,`${t}.failed_iteration_count`),no_progress_count:kt(r.no_progress_count,`${t}.no_progress_count`),...i===void 0?{}:{stop_reason:i},execution_failure_count:kt(r.execution_failure_count,`${t}.execution_failure_count`),previous_unresolved_ids:n,next_action:XA(r.next_action,`${t}.next_action`)}}function jY(e,t){let r=`Native acceptance[${t}]`,n=Zt(e,r);jr(n,new Set(["id","source","text","result","reason"]),r);let i=bt(n.id,`${r}.id`);if(!EY.test(i))throw new Error(`${r}.id must use A1, A2, ...`);return{id:i,source:Oh(n.source,`${r}.source`),text:bt(n.text,`${r}.text`),result:Vt(n.result,["pending","passed","failed","blocked"],`${r}.result`),reason:n.reason===null?null:Ln(n.reason,`${r}.reason`)}}function ZA(e,t){let r=`Native builder_handoff.checks[${t}]`,n=Zt(e,r);return jr(n,new Set(["name","result","note"]),r),{name:Ln(n.name,`${r}.name`),result:Vt(n.result,Hu,`${r}.result`),note:n.note===null?null:Ln(n.note,`${r}.note`)}}function Ti(e){return qn(e,"Native reported checks",(t,r)=>{let n=Zt(t,`Native reported checks[${r}]`);return ZA({name:Ct(bt(n.name,"Reported check name")),result:n.result,note:n.note==null?null:Ct(bt(n.note,"Reported check note"))},r)})}function $Y(e){let t="Native builder_handoff",r=Zt(e,t);jr(r,new Set(["candidate_id","identity_provider","builder_execution_ref","iteration","summary","addressed_acceptance_ids","acceptance_review","checks","checks_truncated","known_limits","known_limits_truncated","review","submitted_at","raw_input_ref"]),t);let n=jh(r.addressed_acceptance_ids,`${t}.addressed_acceptance_ids`);gs(n,`${t}.addressed_acceptance_ids`);let i=r.review===null||r.review===void 0?null:Zt(r.review,`${t}.review`);return i&&jr(i,new Set(["status","summary","reviewer_execution_ref"]),`${t}.review`),{candidate_id:bt(r.candidate_id,`${t}.candidate_id`),identity_provider:bt(r.identity_provider,`${t}.identity_provider`),builder_execution_ref:bt(r.builder_execution_ref,`${t}.builder_execution_ref`),iteration:kt(r.iteration,`${t}.iteration`,1),summary:Ln(r.summary,`${t}.summary`),addressed_acceptance_ids:n,...r.acceptance_review===void 0?{}:{acceptance_review:Nm(r.acceptance_review)},checks:qn(r.checks,`${t}.checks`,ZA),checks_truncated:zc(r.checks_truncated,`${t}.checks_truncated`),known_limits:qn(r.known_limits,`${t}.known_limits`,(o,a)=>Ln(o,`${t}.known_limits[${a}]`)),known_limits_truncated:zc(r.known_limits_truncated,`${t}.known_limits_truncated`),review:i?{status:Vt(i.status,["passed"],`${t}.review.status`),summary:Ln(i.summary,`${t}.review.summary`),reviewer_execution_ref:bt(i.reviewer_execution_ref,`${t}.review.reviewer_execution_ref`)}:null,submitted_at:Kc(r.submitted_at,`${t}.submitted_at`),...r.raw_input_ref!==void 0?{raw_input_ref:bt(r.raw_input_ref,`${t}.raw_input_ref`)}:{}}}function DY(e,t){let r=`Native blockers[${t}]`,n=Zt(e,r);jr(n,new Set(["owner","reason","acceptance_ids","resolution_action"]),r);let i=jh(n.acceptance_ids,`${r}.acceptance_ids`);return gs(i,`${r}.acceptance_ids`),{owner:Vt(n.owner,["builder","runtime","verifier","user","external"],`${r}.owner`),reason:Ln(n.reason,`${r}.reason`),acceptance_ids:i,resolution_action:Vt(n.resolution_action,["return-build","retry-verifier","resolve-verifier-blocker","confirm-verifier-unavailable","await-user","wait-external"],`${r}.resolution_action`)}}function BY(e,t){let r=`Native verification.checks[${t}]`,n=Zt(e,r);return jr(n,new Set(["id","name","argv_display","argv_truncated","cwd_ref","status","exit_code","duration_ms"]),r),{id:bt(n.id,`${r}.id`),name:Ln(n.name,`${r}.name`),argv_display:qn(n.argv_display,`${r}.argv_display`,(i,o)=>Ln(i,`${r}.argv_display[${o}]`)),argv_truncated:zc(n.argv_truncated,`${r}.argv_truncated`),cwd_ref:Oh(n.cwd_ref,`${r}.cwd_ref`,!0),status:Vt(n.status,["passed","failed","interrupted"],`${r}.status`),exit_code:xY(n.exit_code,`${r}.exit_code`),duration_ms:kt(n.duration_ms,`${r}.duration_ms`)}}function WY(e){let t="Native verification",r=Zt(e,t);jr(r,new Set(["candidate_id","identity_provider","verifier_execution_ref","iteration","attempt","assurance","verdict","checks","reported_checks","summary","risks","risks_truncated","completed_at"]),t);let n=qn(r.checks,`${t}.checks`,BY);gs(n.map(o=>o.id),`${t}.checks IDs`);let i=bt(r.identity_provider,`${t}.identity_provider`);return{candidate_id:bt(r.candidate_id,`${t}.candidate_id`),identity_provider:i,verifier_execution_ref:bt(r.verifier_execution_ref,`${t}.verifier_execution_ref`),iteration:kt(r.iteration,`${t}.iteration`,1),attempt:kt(r.attempt,`${t}.attempt`,1),assurance:r.assurance===void 0?i==="skill-coordinated"?"skill-coordinated":"host-attested":Vt(r.assurance,["host-attested","self-reviewed","skill-coordinated","semantic-verification-unavailable","user-confirmed-degraded"],`${t}.assurance`),verdict:Vt(r.verdict,Ua,`${t}.verdict`),checks:n,...r.reported_checks===void 0?{}:{reported_checks:qn(r.reported_checks,`${t}.reported_checks`,ZA)},summary:Ln(r.summary,`${t}.summary`),risks:qn(r.risks,`${t}.risks`,(o,a)=>Ln(o,`${t}.risks[${a}]`)),risks_truncated:zc(r.risks_truncated,`${t}.risks_truncated`),completed_at:Kc(r.completed_at,`${t}.completed_at`)}}function yj(e,t){let r=`Native history[${t}]`,n=Zt(e,r);jr(n,new Set(["goal_cycle","iteration","attempt","outcome","unresolved_ids","summary","completed_at"]),r);let i=jh(n.unresolved_ids,`${r}.unresolved_ids`);return gs(i,`${r}.unresolved_ids`),{goal_cycle:kt(n.goal_cycle,`${r}.goal_cycle`,1),iteration:kt(n.iteration,`${r}.iteration`),attempt:kt(n.attempt,`${r}.attempt`),outcome:Vt(n.outcome,["pass","fail","blocked","execution-error","recovery"],`${r}.outcome`),unresolved_ids:i,summary:Ln(n.summary,`${r}.summary`),completed_at:Kc(n.completed_at,`${r}.completed_at`)}}function qY(e){let t="Native history_overflow.outcome_counts",r=Zt(e,t),n=["pass","fail","blocked","execution-error","recovery"];return jr(r,new Set(n),t),{pass:kt(r.pass,`${t}.pass`),fail:kt(r.fail,`${t}.fail`),blocked:kt(r.blocked,`${t}.blocked`),"execution-error":kt(r["execution-error"],`${t}.execution-error`),recovery:kt(r.recovery,`${t}.recovery`)}}function LY(e){let t="Native history_overflow",r=Zt(e,t);jr(r,new Set(["dropped_entries","first_dropped_at","last_dropped_at","outcome_counts"]),t);let n=kt(r.dropped_entries,`${t}.dropped_entries`),i=r.first_dropped_at===null?null:Kc(r.first_dropped_at,`${t}.first_dropped_at`),o=r.last_dropped_at===null?null:Kc(r.last_dropped_at,`${t}.last_dropped_at`);if(n===0&&(i!==null||o!==null))throw new Error("Native empty history overflow cannot contain dropped timestamps");if(n>0&&(i===null||o===null))throw new Error("Native non-empty history overflow requires dropped timestamps");let a=qY(r.outcome_counts);if(Object.values(a).reduce((c,l)=>c+l,0)!==n)throw new Error("Native history overflow outcome count must equal dropped_entries");return{dropped_entries:n,first_dropped_at:i,last_dropped_at:o,outcome_counts:a}}function VY(e){if(e.verifier_action){if(Ph(e.verifier_action),e.verifier_action.runId!==e.name)throw new Error("Native Verifier action belongs to another change");if(e.phase==="verify"&&e.status==="active"&&e.loop.next_action==="await-verifier-result"&&["pending","running","unknown"].includes(e.verifier_action.status)&&!gj(e,e.verifier_action))throw new Error("Native Verifier action is stale for the current candidate or attempt")}let t=new Set(e.acceptance.map(r=>r.id));for(let r of e.loop.previous_unresolved_ids)if(!t.has(r))throw new Error(`Native loop references unknown acceptance ID ${r}`);for(let r of e.builder_handoff?.addressed_acceptance_ids??[])if(!t.has(r))throw new Error(`Native builder handoff references unknown ID ${r}`);e.builder_handoff?.acceptance_review&&Ju(e.acceptance,e.builder_handoff.acceptance_review);for(let r of e.blockers)for(let n of r.acceptance_ids)if(!t.has(n))throw new Error(`Native blocker references unknown ID ${n}`);if(e.builder_handoff){if(!(e.builder_handoff.iteration===e.loop.iteration||e.phase==="build"&&e.loop.stage==="repairing"&&e.builder_handoff.iteration===e.loop.iteration-1))throw new Error("Native builder handoff iteration is not current or the prior repair result");if(e.builder_handoff.review?.reviewer_execution_ref===e.builder_handoff.builder_execution_ref)throw new Error("Native reviewer execution ref must differ from the Builder execution ref")}if(e.verification){if(!e.builder_handoff)throw new Error("Native verification requires a builder handoff");if(e.verification.candidate_id!==e.builder_handoff.candidate_id)throw new Error("Native verification candidate must match the builder handoff");if(e.verification.identity_provider!==e.builder_handoff.identity_provider)throw new Error("Native Builder and Verifier identity providers must match");let r=["skill-coordinated","semantic-verification-unavailable","user-confirmed-degraded"].includes(e.verification.assurance);if(e.verification.assurance!=="self-reviewed"&&r!==(e.verification.identity_provider==="skill-coordinated"))throw new Error("Native verification assurance does not match its identity provider");if(e.verification.assurance==="self-reviewed"&&e.verification.verifier_execution_ref!==e.builder_handoff.builder_execution_ref)throw new Error("Native self-reviewed verification must use the Builder session");if(e.verification.assurance==="semantic-verification-unavailable"&&e.verification.verdict!=="blocked")throw new Error("Native unavailable semantic verification must remain blocked");if(e.verification.assurance==="user-confirmed-degraded"&&e.verification.verdict!=="pass")throw new Error("Native user-confirmed degraded verification must be passing");if(e.verification.assurance!=="self-reviewed"&&e.verification.verifier_execution_ref===e.builder_handoff.builder_execution_ref)throw new Error("Native Builder and Verifier execution refs must differ");let n=e.verification.iteration===e.loop.iteration&&e.verification.attempt===e.loop.attempt,i=e.phase==="build"&&e.loop.stage==="repairing"&&e.verification.iteration===e.loop.iteration-1&&e.verification.iteration===e.builder_handoff.iteration;if(!n&&!i)throw new Error("Native verification iteration and attempt do not match a stable loop result")}}function MY(e){if(!{shape:new Set(["shape","await-user","blocked"]),build:new Set(["building","repairing","await-user","blocked"]),verify:new Set(["verify-ready","await-user","blocked"]),archive:new Set(["archive-ready","await-user","blocked","done"])}[e.phase].has(e.loop.stage))throw new Error(`Native loop stage ${e.loop.stage} is invalid for phase ${e.phase}`);let r=e.status==="await-user"?"await-user":e.status==="blocked"?"blocked":e.status==="done"?"done":null;if(r!==null&&e.loop.stage!==r)throw new Error(`Native status ${e.status} requires loop stage ${r}`);if(e.status==="active"&&["await-user","blocked","done"].includes(e.loop.stage))throw new Error(`Native active status cannot use loop stage ${e.loop.stage}`);if(e.archived!==(e.status==="done"))throw new Error("Native archived must be true exactly when status is done");if(e.archived&&e.phase!=="archive")throw new Error("Native archived state must be in Archive");if(e.verification_result==="pass"){if(e.verification?.verdict!=="pass")throw new Error("Native pass requires a persisted passing verification");if(e.acceptance.some(n=>n.result!=="passed"))throw new Error("Native pass requires every acceptance item to pass");if(e.verification.checks.some(n=>n.status!=="passed"))throw new Error("Native pass requires every persisted check to pass")}if(e.verification?.assurance==="semantic-verification-unavailable"&&(e.phase!=="verify"||e.status!=="await-user"||e.verification_result!=="blocked"||e.loop.next_action!=="confirm-verifier-unavailable"))throw new Error("Native unavailable semantic verification must await explicit user confirmation");if(e.verification_report!==null&&e.verification===null)throw new Error("Native verification report requires persisted verification")}function M(e){let t=Zt(e,"Native portable state");if(jr(t,_Y,"Native portable state"),t.schema!==hs)throw new Error(`Native portable state schema must be ${hs}`);let r=bt(t.name,"Native state name");if(!NY.test(r))throw new Error("Native state name is invalid");if(t.brief!=="brief.md")throw new Error("Native state brief must be brief.md");let n=qn(t.spec_changes,"Native spec_changes",PY);gs(n.map(s=>s.capability),"Native spec change capabilities");let i=qn(t.acceptance,"Native acceptance",jY);gs(i.map(s=>s.id),"Native acceptance IDs");let o=qn(t.history,"Native history",yj);if(o.length>50)throw new Error(`Native history cannot exceed ${50} entries`);let a={schema:hs,name:r,language:Vt(t.language,["en","zh-CN"],"Native state language"),phase:Vt(t.phase,["shape","build","verify","archive"],"Native state phase"),status:Vt(t.status,["active","await-user","blocked","done"],"Native state status"),state_version:kt(t.state_version,"Native state_version",1),brief:"brief.md",...t.document_constraints_version===void 0?{}:t.document_constraints_version===1||t.document_constraints_version===2||t.document_constraints_version===3?{document_constraints_version:t.document_constraints_version}:(()=>{throw new Error("Native document_constraints_version must be 1, 2, or 3")})(),...t.shape_confirmation_hash===void 0?{}:{shape_confirmation_hash:wj(t.shape_confirmation_hash,"Native Shape confirmation hash")},...(t.children_contract_ref??t.children_contract_hash)===void 0?{}:{children_contract_ref:bt(t.children_contract_ref??t.children_contract_hash,"Native children approval reference")},...t.children_contract_ref!==void 0&&t.children_contract_hash!==void 0?{children_contract_hash:bt(t.children_contract_hash,"Legacy children approval reference")}:{},...t.children_contract===void 0?{}:{children_contract:IY(t.children_contract,i)},...t.coordination_mode===void 0?{}:{coordination_mode:Vt(t.coordination_mode,["multi-session","single-session"],"Native coordination mode")},spec_changes:n,workspace:TY(t.workspace),loop:OY(t.loop),acceptance:i,builder_handoff:t.builder_handoff===null?null:$Y(t.builder_handoff),...t.verifier_action===void 0?{}:{verifier_action:jx(t.verifier_action)},blockers:qn(t.blockers,"Native blockers",DY),verification:t.verification===null?null:WY(t.verification),history:o,history_overflow:LY(t.history_overflow),verification_result:Vt(t.verification_result,["pending","pass","fail","blocked"],"Native verification_result"),verification_report:t.verification_report===null?null:Vt(t.verification_report,["verification.md"],"Native verification_report"),archived:zc(t.archived,"Native archived"),created_at:Kc(t.created_at,"Native created_at")};return VY(a),MY(a),a}function Gc(e){let t=e.createdAt instanceof Date?e.createdAt.toISOString():e.createdAt??new Date().toISOString();return M({schema:hs,name:e.name,language:e.language,phase:"shape",status:"active",state_version:1,brief:"brief.md",spec_changes:[],workspace:e.workspace??{isolation:"current",change_branch:null,target_branch:null,finish:null},loop:{stage:"shape",goal_cycle:1,iteration:0,attempt:0,retry_epoch:0,failed_iteration_count:0,no_progress_count:0,execution_failure_count:0,previous_unresolved_ids:[],next_action:e.nextAction??null},acceptance:[],builder_handoff:null,blockers:[],verification:null,history:[],history_overflow:Uc(),verification_result:"pending",verification_report:null,archived:!1,created_at:t})}function vn(e,t){let r=M(e),n=yj(t,r.history.length),i=[...r.history,n],o={...r.history_overflow,outcome_counts:{...r.history_overflow.outcome_counts}};for(;i.length>50;){let a=i.shift();o.dropped_entries+=1,o.first_dropped_at??=a.completed_at,o.last_dropped_at=a.completed_at,o.outcome_counts[a.outcome]+=1}return M({...r,history:i,history_overflow:o})}async function Jt(e){let t=await RY.readFile(e,"utf8");return M(fa(t,"Native portable state"))}async function $d(e,t,r={}){let n=M(t);await qe(e,(0,vj.stringify)(n),r)}async function FY(e,t){let r=Th.get(e)??Promise.resolve(),n,i=new Promise(a=>{n=a}),o=r.then(()=>i);Th.set(e,o),await r;try{return await t()}finally{n(),Th.get(e)===o&&Th.delete(e)}}async function kj(e){return FY(e.file,async()=>{let t=kt(e.expectedStateVersion,"Native expected state version",1),r=M(e.next);if(r.state_version!==t+1)throw new Error("Native CAS next state_version must increment exactly once");let n=await Jt(e.file);if(n.state_version===r.state_version&&JSON.stringify(n)===JSON.stringify(r))return n;if(n.state_version!==t)throw new jd(t,n.state_version);return await $d(e.file,r,{...e.containedRoot?{containedRoot:e.containedRoot}:{},beforeCommit:async()=>{let i=await Jt(e.file);if(i.state_version!==t)throw new jd(t,i.state_version)}}),r})}var vj,NY,SY,EY,CY,_Y,jd,Th,Se=x(()=>{"use strict";io();Sm();Cr();Ja();vj=dr(Ur(),1);Ka();Qc();Td();dt();Jc();NY=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,SY=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,EY=/^A[1-9][0-9]*$/u,CY=/^[a-f0-9]{64}$/u,_Y=new Set(["schema","name","language","phase","status","state_version","brief","document_constraints_version","shape_confirmation_hash","shape_semantic_snapshot","children_contract_ref","children_contract_hash","children_contract","coordination_mode","spec_changes","workspace","loop","acceptance","builder_handoff","verifier_action","blockers","verification","history","history_overflow","verification_result","verification_report","archived","created_at","run_checkpoint","archive_receipt","application_checkpoint"]);jd=class extends Error{constructor(r,n){super(`Native state version conflict: expected ${r}, got ${n}`);this.expectedStateVersion=r;this.actualStateVersion=n;this.name="NativePortableStateVersionConflictError"}expectedStateVersion;actualStateVersion;code="native-state-version-conflict"};Th=new Map});function bj(e){return{phase:e.phase,...e.task?{task:e.task}:{},contextMode:"snapshot",commandArgs:["comet","task",e.projectRoot??".","--task",e.task??"<original-task>","--phase",e.phase,"--session",e.sessionId??"<receiving-session-id>","--context-mode","snapshot",...e.workflow&&e.change?["--workflow",e.workflow,"--change",e.change]:[],"--json"],instruction:[e.language==="zh-CN"?"领取响应已有 contextDelivery 时直接读取 context[].text,不重复检索;上下文丢失时使用 contextActions.restore。其他情况下,首次进入本阶段、交接给新 Agent 或上下文恢复后,由接收方用自己的会话标识和原始请求执行一次本命令,将返回的 context[].text 加入上下文;普通连续执行无需重复获取。将适用偏好和项目约束交给执行者与审查者。Skill 由平台按实际可用能力加载;不兼容或不可用时说明原因。已交付偏好不代表已加载或遵循 Skill;偏好不能代替 Runtime 检查或阶段授权。空结果或获取失败时沿用明确指令继续,不循环重试。":"When the claim response includes contextDelivery, read context[].text without another retrieval; use contextActions.restore after context loss. Otherwise, on first entering this phase, handing off to a new Agent, or restoring context, the receiver runs this command once with its own session ID and the original task, then adds context[].text to context. Do not repeat during uninterrupted work. Pass applicable preferences and project constraints to implementers and reviewers. Load Skills using actual host capabilities; explain unavailable or incompatible choices. Delivery does not prove a Skill was loaded or followed; preferences do not replace Runtime checks or authorization. Continue with explicit instructions after empty or unavailable retrieval; do not loop on retries.",e.instruction].filter(Boolean).join(" ")}}var Aj=x(()=>{"use strict"});import HY from"node:path";function Rj(e,t){let r=t.actions.map(o=>o.stepId==="repair.implementation"&&o.status==="succeeded").lastIndexOf(!0),n=t.actions[r];if(r<0||n?.outcome?.output?.driftKind!=="report-drift"||t.actions.slice(r+1).some(o=>o.stepId==="verify.report"&&o.status==="succeeded"))return null;let i=t.input.artifactRootRef;return typeof i!="string"?null:{ref:HY.posix.join(i.replaceAll("\\","/"),"comet","changes",e.name,"verification.md"),instruction:e.language==="zh-CN"?"读取用户修改的原验证报告,核对其补充并作为待验证输入;不得将旧报告当作新候选已通过的证据。":"Read the user-edited verification report and assess its notes as inputs; do not treat the old report as proof that the new candidate passed."}}function Dd(e,t){let r=e.builder_handoff?.candidate_id??null,n=new Map;for(let o of t.actions){if(!["verify.checks","verify.requested-checks"].includes(o.stepId)||!o.outcome)continue;let a=o.outcome.output;if(a?.candidateId===r)for(let s of a.checks??[])n.set(s.id,{id:s.id,status:s.status,actionId:o.id,logRef:s.logRef,inputScope:s.inputScope?.kind??"project"})}let i=[...t.actions].reverse().find(o=>o.stepId==="verify.verifier"&&o.status==="succeeded");return{schema:"comet.native.repair-context.v1",previousCandidateId:r,unresolvedAcceptanceIds:e.loop.previous_unresolved_ids,previousVerifierActionId:i?.id??null,previousChecks:[...n.values()],...Rj(e,t)?{userEditedReport:Rj(e,t)}:{},candidateHandling:"review-existing-work-first",instruction:e.language==="zh-CN"?"先核对并保留用户当前修改。若现有工作已满足已确认需求,原样提交后继候选,无需为推进流程重新写入;确有遗漏时只修复遗漏。旧检查由 Runtime 判断复用,新候选仍需独立验收全部验收项。":"Inspect and preserve the user’s current changes first. If the existing work satisfies the approved requirements, submit it unchanged as the successor candidate; do not rewrite files merely to advance. Repair only actual gaps. Runtime decides check reuse and the successor still requires independent verification of every acceptance criterion."}}function Yc(e){return bj({...e,workflow:"native",change:e.name,instruction:e.language==="zh-CN"?"原始请求缺失时从当前 brief 恢复目标。向 Builder、Verifier 或子任务交接时不转交 Builder 的自评结论,保留独立只读验收要求。":"Recover a missing task goal from the current brief. Hand off to the Builder, Verifier or child without Builder self-assessment, preserving independent read-only verification."})}var Bd=x(()=>{"use strict";Aj()});function tR(e,t){if(typeof e!="string"||e.trim().length===0||e.includes("\0"))throw new Error(`${t} is invalid`);return e}function rR(){let e=new WeakSet;return Object.freeze({captureExecutionIdentity(t){tR(t.identityProvider,"Native identity provider");let r=Object.freeze({identityProvider:$r,executionRef:tR(t.executionRef,"Native execution ref"),[Nj]:!0});return e.add(r),r},envelopeVerifierResponse(t){if(!e.has(t.identity))throw new Error("Native execution identity was not captured by this Runner channel");return Object.freeze({candidateId:tR(t.candidateId,"Native candidate ID"),identityProvider:t.identity.identityProvider,verifierExecutionRef:t.identity.executionRef,payload:t.payload,[Sj]:!0})}})}function nR(e){return typeof e=="object"&&e!==null&&e[Sj]===!0}function Ej(e){return typeof e=="object"&&e!==null&&e[Nj]===!0}var Nj,Sj,$r,vs=x(()=>{"use strict";Nj=Symbol("comet.native.trusted-execution-identity"),Sj=Symbol("comet.native.trusted-verifier-envelope"),$r="skill-coordinated"});function $h(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function Cj(e,t){if(!Number.isSafeInteger(e)||e<0)throw new Error(`${t} must be a non-negative integer`);return e}function Dh(e,t){if(typeof e!="string"||e.trim().length===0)throw new Error(`${t} must be non-empty text`);return e}function Bh(e,t="/acceptance"){if(!Array.isArray(e))throw new Error("Native Verifier acceptance must be an array");return e.map((r,n)=>{let i=$h(r,`Native Verifier acceptance ${n}`);Qa(i,["id","result","reason"],`Native Verifier acceptance ${n}`,`${t}/${n}`);let o=Dh(i.id,`Native Verifier acceptance ${n} ID`),a=Sc(i.result,Qu,`Native Verifier acceptance ${o} result`);return{id:o,result:a,reason:Dh(i.reason,`Native Verifier acceptance ${o} reason`)}})}function QY(e,t){let r=$h(e,"Native Verifier final result");Qa(r,["iteration","attempt","verdict","acceptance","risks","summary",...Object.hasOwn(r,"requestReview")?["requestReview"]:[]],"Native Verifier final result",t);let n=Sc(r.verdict,Ua,"Native Verifier verdict");if(!Array.isArray(r.risks)||!r.risks.every(o=>typeof o=="string"))throw new Error("Native Verifier risks must be text entries");let i;if(r.requestReview!==void 0){let o=$h(r.requestReview,"Native requestReview");Qa(o,["result","reason"],"Native requestReview",`${t}/requestReview`),i={result:Sc(o.result,Rm,"Native requestReview result"),reason:Dh(o.reason,"Native requestReview reason")}}return{...i?{requestReview:i}:{},iteration:Cj(r.iteration,"Native Verifier iteration"),attempt:Cj(r.attempt,"Native Verifier attempt"),verdict:n,acceptance:Bh(r.acceptance,`${t}/acceptance`),risks:r.risks,summary:Dh(r.summary,"Native Verifier summary")}}function _j(e,t=""){let r=$h(e,"Native Verifier response");if(r.kind==="final-result")return Qa(r,["kind","result"],"Native Verifier response",t),{kind:"final-result",result:QY(r.result,`${t}/result`)};throw new Error(`Native Verifier response kind must be one of: ${Ex.join(", ")}`)}function Ij(e){if(!nR(e.envelope))throw new Error("Native Verifier result must come from the trusted Runner channel");let{envelope:t,binding:r}=e;if(t.candidateId!==r.candidateId)throw new Error("Native Verifier result does not match the current candidate");if(t.identityProvider!==r.identityProvider)throw new Error("Native Verifier identity provider does not match the Builder provider");if(r.requireIndependentSession!==!1&&t.verifierExecutionRef===r.builderExecutionRef)throw new Error("Native Builder and Verifier must be different executions");let n=_j(t.payload),i=n.result.iteration,o=n.result.attempt;if(i!==r.iteration||o!==r.attempt)throw new Error(`Native Verifier result is stale for the current iteration or attempt: expected iteration=${r.iteration}, attempt=${r.attempt}; received iteration=${i}, attempt=${o}. Inspect the current action and use its outputTemplate before submitting a new outcomeId`);let a=Wh(n.result,r);return{...n,result:{...n.result,acceptance:a}}}function Wh(e,t){Bh(e.acceptance);let r=[...t.acceptanceIds],n=new Set(t.knownAcceptanceIds??r),i=new Set(t.previouslyPassedAcceptanceIds??[]),o=r.filter(h=>!n.has(h)),a=[...i].filter(h=>!n.has(h));if(o.length>0||a.length>0)throw new Error("Native Verifier acceptance binding is internally inconsistent");let s=new Set(r),c=e.acceptance.map(({id:h})=>h),l=c.filter((h,g)=>c.indexOf(h)!==g),u=c.filter(h=>!n.has(h)),f=r.filter(h=>!c.includes(h)),d=e.acceptance.filter(({id:h,result:g})=>s.has(h)||!n.has(h)?!1:!i.has(h)||g!=="passed").map(({id:h,result:g})=>`${h}=${g}`);if(l.length>0||u.length>0||f.length>0||d.length>0)throw new Error(`Native Verifier acceptance coverage is invalid (duplicate: ${[...new Set(l)].join(", ")||"none"}; unknown: ${u.join(", ")||"none"}; missing: ${f.join(", ")||"none"}; out-of-scope: ${d.join(", ")||"none"}). Return each required scope ID exactly once and no other acceptance IDs.`);let p=e.acceptance.filter(({id:h})=>s.has(h));if(!t.requiredChecksPassed&&e.verdict==="pass")throw new Error("Native verification cannot pass before every required check succeeds");let m=p.map(({result:h})=>h);if(e.verdict==="pass"&&m.some(h=>h!=="passed"))throw new Error("Native pass requires every acceptance criterion to pass");if(e.verdict==="fail"&&!m.includes("failed"))throw new Error("Native fail requires at least one failed acceptance criterion");if(e.verdict==="blocked"&&!m.includes("blocked"))throw new Error("Native blocked verdict requires at least one blocked acceptance criterion");return p}var Wd=x(()=>{"use strict";Ja();Am();vs()});function Xc(e,t){if(!UY.test(e))throw new Error(`${t} must be a Git commit`)}function iR(e){return structuredClone(e)}function oR(e,t){e.history.push({...t,at:new Date().toISOString()}),e.history.length>256&&e.history.splice(0,e.history.length-256)}function JY(e,t){let r=new Map(t.map(({name:n,status:i})=>[n,i]));return e.every(n=>r.get(n)==="integrated")}function Lh(e){Xc(e.targetCommit,"Native Supervisor target commit");let t=new Set(e.contract.children.map(({name:n})=>n)),r=e.contract.children.map(n=>({name:n.name,summary:n.summary,dependsOn:[...n.depends_on],status:n.depends_on.length===0?"ready":"pending",baseCommit:null,candidateCommit:null,verifiedCommit:null,integrationCommit:null,verification:null,checks:[],blocker:null,projectRoot:null,task:null,acceptanceScope:oi(e.contract,n.name),builderFailureCount:0}));for(let n of r)for(let i of n.dependsOn)if(!t.has(i))throw new Error(`Native Supervisor child ${n.name} depends on unknown child ${i}`);return{schema:qd,stateVersion:1,parent:e.parent,integration:{branch:e.integrationBranch,worktree:e.integrationWorktree,targetBranch:e.targetBranch,targetCommit:e.targetCommit,headCommit:e.targetCommit},children:r,history:[],finalVerification:{status:"pending",summary:null}}}function oi(e,t){let r=e.children.find(n=>n.name===t);return r.covers.length>0?r.covers.map(n=>({id:n,source:e.acceptance_index?.[n]?.source??"brief.md",text:e.acceptance_index?.[n]?.text??n})):[{id:`child:${t}`,source:"children.yaml",text:r.summary??t}]}function Vh(e){let t=iR(e.state),r=new Map(e.contract.children.map(i=>[i.name,i])),n=new Map(t.children.map(i=>[i.name,i]));for(let i of t.children){let o=r.get(i.name);if(!o){if(i.status!=="archived")throw new Error(`Native Supervisor child ${i.name} cannot be removed before Archive`);continue}if((i.status==="integrated"||i.status==="archived")&&(o.summary!==i.summary||o.depends_on.join("\0")!==i.dependsOn.join("\0")))throw new Error(`Native Supervisor integrated child ${i.name} history is immutable`);i.summary=o.summary,i.dependsOn=[...o.depends_on];let a=oi(e.contract,i.name);i.acceptanceScope=a,i.builderFailureCount??=0}for(let i of e.contract.children)n.has(i.name)||t.children.push({name:i.name,summary:i.summary,dependsOn:[...i.depends_on],status:i.depends_on.every(o=>t.children.some(({name:a,status:s})=>a===o&&s==="integrated"))?"ready":"pending",baseCommit:null,candidateCommit:null,verifiedCommit:null,integrationCommit:null,verification:null,checks:[],blocker:null,projectRoot:null,task:null,acceptanceScope:oi(e.contract,i.name),builderFailureCount:0});for(let i of t.children)(i.status==="pending"||i.status==="ready")&&i.task===null&&i.candidateCommit===null&&(i.status=JY(i.dependsOn,t.children)?"ready":"pending");return t.stateVersion+=1,t}function Mh(e){let t=e.children.every(n=>n.acceptanceScope&&n.acceptanceScope.length>0&&(!n.task||n.task.acceptance&&n.task.acceptance.length>0)),r=e.children.map(n=>({name:n.name,summary:n.summary,dependsOn:[...n.dependsOn],covers:n.acceptanceScope?.map(({id:i})=>i)??[],status:(n.status==="ready"||n.status==="active")&&n.blocker&&[...e.history].reverse().find(i=>i.child===n.name)?.kind==="task-blocked"?"blocked":n.status,phase:null,projectRoot:n.projectRoot??n.task?.projectRoot??null,message:t?n.blocker:"Supervisor acceptance scope is unavailable; restore children.yaml and confirm Shape before continuing",builderFailureCount:n.builderFailureCount??0}));return{contractRef:null,supervisorStateVersion:e.stateVersion,confirmed:t,parentBranch:e.integration.branch,children:r,readyChildren:t?r.filter(({status:n})=>n==="ready").map(({name:n})=>n):[],allDone:t&&r.every(({status:n})=>n==="integrated"||n==="archived")}}var UY,qd,qh,ai=x(()=>{"use strict";Ja();Bd();Wd();UY=/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u;qd="comet.native.supervisor.v2",qh=3});import{promises as xj}from"node:fs";import Ld from"node:path";function Pj(e,t){return Ld.join(Rc(e,t),"supervisor")}function Fh(e,t){return Ld.join(Pj(e,t),"state.json")}function Tj(e){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Native Supervisor state must be an object");let t=e;if(t.schema!==qd)throw new Error(`Native Supervisor state schema must be ${qd}`);if(!Number.isSafeInteger(t.stateVersion)||typeof t.stateVersion!="number"||t.stateVersion<1)throw new Error("Native Supervisor state version is invalid");if(typeof t.parent!="string"||!t.parent)throw new Error("Native Supervisor state parent is invalid");if(!t.integration||typeof t.integration!="object")throw new Error("Native Supervisor integration state is missing");for(let[i,o]of Object.entries(t.integration))if(i!=="checkExecution"&&(typeof o!="string"||o.length===0))throw new Error(`Native Supervisor integration field ${i} is invalid`);if(Xc(t.integration.targetCommit,"Native Supervisor target commit"),Xc(t.integration.headCommit,"Native Supervisor integration head commit"),!Array.isArray(t.children))throw new Error("Native Supervisor children are invalid");if(!Array.isArray(t.history))throw new Error("Native Supervisor history is invalid");if(!t.finalVerification||!["pending","passed","failed","incomplete"].includes(t.finalVerification.status)||t.finalVerification.summary!==null&&typeof t.finalVerification.summary!="string")throw new Error("Native Supervisor final verification is invalid");if(t.finalVerification.layers){let i=t.finalVerification.layers;if(!["complete","incomplete"].includes(i.childVerification)||!["complete","incomplete"].includes(i.parentIntegration)||!Array.isArray(i.parentChecks)||!i.parentChecks.every(o=>typeof o=="string")||!Array.isArray(i.notRerun)||!i.notRerun.every(o=>typeof o=="string")||!Array.isArray(i.incomplete)||!i.incomplete.every(o=>typeof o=="string"))throw new Error("Native Supervisor final verification layers are invalid")}for(let i of t.history)if(!i||typeof i!="object"||typeof i.kind!="string"||typeof i.summary!="string"||typeof i.at!="string"||i.child!==null&&typeof i.child!="string"||i.runId!==null&&typeof i.runId!="string")throw new Error("Native Supervisor history event is invalid");let r=new Set,n=new Set;for(let i of t.children){if(!i||typeof i!="object"||typeof i.name!="string")throw new Error("Native Supervisor child state is invalid");if(r.has(i.name))throw new Error(`Native Supervisor child ${i.name} is duplicated`);if(r.add(i.name),!Array.isArray(i.dependsOn)||!i.dependsOn.every(o=>typeof o=="string"))throw new Error(`Native Supervisor child ${i.name} dependencies are invalid`);if(typeof i.summary!="string"&&i.summary!==null)throw new Error(`Native Supervisor child ${i.name} summary is invalid`);if(i.builderFailureCount!==void 0&&(!Number.isSafeInteger(i.builderFailureCount)||i.builderFailureCount<0))throw new Error(`Native Supervisor child ${i.name} Builder failure count is invalid`);if(i.projectRoot!==void 0&&i.projectRoot!==null&&(typeof i.projectRoot!="string"||i.projectRoot.length===0))throw new Error(`Native Supervisor child ${i.name} projectRoot is invalid`);for(let[o,a]of[["base",i.baseCommit],["candidate",i.candidateCommit],["verified",i.verifiedCommit],["integration",i.integrationCommit]])a!==null&&Xc(a,`Native Supervisor child ${i.name} ${o} commit`);if(!Array.isArray(i.checks)||!Array.isArray(i.verification?.checks??[]))throw new Error(`Native Supervisor child ${i.name} evidence is invalid`);if(i.task!==null){if(!i.task||typeof i.task!="object")throw new Error(`Native Supervisor child ${i.name} task is invalid`);if(!["builder","verifier"].includes(i.task.role)||i.task.child!==i.name||typeof i.task.projectRoot!="string"||i.task.projectRoot.length===0||typeof i.task.runId!="string"||i.task.runId.length===0)throw new Error(`Native Supervisor child ${i.name} task identity is invalid`);if(Xc(i.task.baseCommit,`Native Supervisor child ${i.name} task base commit`),n.has(i.task.runId))throw new Error(`Native Supervisor task runId ${i.task.runId} is duplicated`);if(n.add(i.task.runId),i.task.role==="verifier"&&i.task.baseCommit!==i.candidateCommit)throw new Error(`Native Supervisor child ${i.name} verifier base commit is invalid`);if(i.task.projectRoot!==i.projectRoot)throw new Error(`Native Supervisor child ${i.name} task projectRoot is invalid`);if(i.task.role==="builder"&&i.status!=="active"||i.task.role==="verifier"&&!["active","needs-reverify"].includes(i.status))throw new Error(`Native Supervisor child ${i.name} task status is invalid`)}}}async function Dr(e,t,r={}){try{let n=await xj.readFile(Fh(e,t),"utf8"),i=JSON.parse(n);if(i&&typeof i=="object"&&Array.isArray(i.children))for(let a of i.children)a.contractRef===void 0&&typeof a.contractHash=="string"&&(a.contractRef=a.contractHash),a.task&&a.task.contractRef===void 0&&typeof a.task.contractHash=="string"&&(a.task.contractRef=a.task.contractHash);if(i&&typeof i=="object"){let a=i;if(a.integration&&delete a.integration.checkExecution,Array.isArray(a.children))for(let s of a.children)s.task&&(delete s.task.checkExecution,delete s.task.checksReason)}if(Tj(i),i.children.some(a=>!a.acceptanceScope||a.task&&!a.task.acceptance))try{let a=e;if(!a.changesDir)throw new Error("Native Supervisor upgrade requires full project paths to recover confirmed acceptance");let{readNativePortableState:s}=await Promise.resolve().then(()=>(Se(),eR)),c=await s(Ld.join(a.changesDir,t,"comet-state.yaml")),l=await pn({changeDir:Ld.join(a.changesDir,t),acceptanceIds:c.acceptance.map(({id:u})=>u),validation:fn(c)});if(!l)throw new Error("Native Supervisor upgrade requires the confirmed children contract");for(let u of i.children)l.contract.children.some(({name:f})=>f===u.name)&&(u.acceptanceScope=oi(l.contract,u.name),u.task&&(u.task.acceptance=structuredClone(u.acceptanceScope),u.task.contractRef=u.contractRef,u.task.verificationBoundary="child-scope-parent-reverifies-all"))}catch(a){if(!r.diagnostics)throw a}let o=e;if(o.changesDir)try{let{readNativePortableState:a}=await Promise.resolve().then(()=>(Se(),eR)),s=await a(Ld.join(o.changesDir,t,"comet-state.yaml"));s.workspace.change_branch&&(i.integration.targetBranch=s.workspace.change_branch)}catch(a){if(a.code!=="ENOENT")throw a}return i}catch(n){if(n.code==="ENOENT")return null;throw n}}async function Hh(e,t){let r=await zY(e,t);if(r.length>0)throw new Error(`Native Supervisor Git binding cannot change while active child tasks exist: ${r.join(", ")}`)}async function zY(e,t){return(await Dr(e,t,{diagnostics:!0}))?.children.filter(({task:n})=>n!==null).map(({name:n})=>n)??[]}async function mo(e,t){Tj(t),await xj.mkdir(e.changesRuntimeDir,{recursive:!0}),await Bt(Fh(e,t.parent),t,{containedRoot:e.changesRuntimeDir})}var Oi=x(()=>{"use strict";dt();Cr();He();ai()});import Qh from"node:path";function aR(...e){if(e.length===0)return Qh.resolve();if(Qh.win32.isAbsolute(e[0])){let t=Qh.win32.resolve(...e);return process.platform==="win32"?t:t.replace(/\\/gu,"/")}return Qh.resolve(...e)}var Oj=x(()=>{"use strict"});import{randomUUID as KY}from"node:crypto";import{promises as Vd,lstatSync as sR,readFileSync as GY,realpathSync as YY}from"node:fs";import ji from"node:path";function Md(e){try{if(te(e,["ls-files","--",Zc]))return!1;let t=ji.join(e,Zc),r=sR(t);if(!r.isFile()||r.isSymbolicLink())return!1;let n=Le(e),i=cR(e);for(let s of[n,ji.dirname(i)]){let c=sR(s);if(c.isSymbolicLink()||!c.isDirectory())return!1}let o=sR(i);if(!o.isFile()||o.isSymbolicLink()||YY(i)!==ji.resolve(i))return!1;let a=JSON.parse(GY(i,"utf8"));return a.created===!0||typeof a.hash=="string"}catch{return!1}}async function jj(e){let t=ji.join(e,Zc);try{await Vd.access(t)}catch(i){if(i.code==="ENOENT")return;throw i}let r=await Ha(e),n=cR(e);await Vd.mkdir(ji.dirname(n),{recursive:!0}),await Bt(n,{created:!0},{containedRoot:r})}function ho(e,t=[]){return pc(e).every(r=>t.some(n=>r===n||r.startsWith(`${n}/`))||r===Zc&&Md(e))}async function lR(e){if(!Md(e))return;let t=await Ha(e),r="native/preserved-configs/"+KY()+".yaml",n=ji.join(t,r);await Vd.mkdir(ji.dirname(n),{recursive:!0}),await Vd.copyFile(ji.join(e,Zc),n),await Bt(cR(e),{created:!0,preservedRef:r},{containedRoot:t}),await Vd.unlink(ji.join(e,Zc))}var Zc,cR,el=x(()=>{"use strict";or();Sr();dt();Zc=".comet/config.yaml",cR=e=>ji.join(Le(e),"native","workspace-config.json")});var ws,ys,Uh,$i,tl=x(()=>{"use strict";ws=class extends Error{constructor(r,n,i){super(`Native change ${r} revision conflict: expected ${n}, actual ${i}`);this.change=r;this.expectedRevision=n;this.actualRevision=i;this.name="NativeChangeRevisionConflictError"}change;expectedRevision;actualRevision;code="native-change-revision-conflict"},ys=class extends Error{constructor(r,n){super(`Native working directory already contains active change${n.length===1?"":"s"} ${n.join(", ")}; create the new change in a separate worktree`);this.requestedIsolation=r;this.activeChanges=n;this.name="NativeWorkspaceIsolationRequiredError"}requestedIsolation;activeChanges;code="native-workspace-isolation-required"},Uh=class extends Error{constructor(r,n,i,o){super(`Canonical spec conflict for ${r}: expected ${n??"(missing)"}, actual ${i??"(missing)"}`);this.capability=r;this.expectedHash=n;this.actualHash=i;this.canonicalPath=o;this.name="NativeSpecConflictError"}capability;expectedHash;actualHash;canonicalPath;code="native-spec-conflict"},$i=class extends Error{constructor(r,n,i){super(r,i);this.preparation=n;this.name="NativeWorkspacePreparationError"}preparation}});import{promises as Fd}from"node:fs";import tn from"node:path";function Wj(e,t){let r=tn.relative(e,t);return r===""||!tn.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${tn.sep}`)}function $j(e){let t={...e.native};return delete t.max_parallel_children,JSON.stringify(t)}async function Jh(e,t){let r=await Te(e);if(r&&t){if($j(r)!==$j(t))throw new Error(`Native worktree configuration differs from the source project: ${tn.join(e,".comet","config.yaml")}`);return!1}return!r&&t?(await no(e,t),await jj(e),!0):!1}async function Dj(e,t){let r=["/.comet/runtime"];if(t&&Wj(e,t)){let l=tn.relative(e,t).replaceAll("\\","/");r.push(`/${l.replace(/\/+$/u,"")}/`)}let n=te(e,["rev-parse","--git-common-dir"]),i=tn.resolve(e,n),o=tn.join(i,"info","exclude"),a="";try{a=await Fd.readFile(o,"utf8")}catch(l){if(l.code!=="ENOENT")throw l}let s=r.filter(l=>!a.split(/\r?\n/u).includes(l));if(s.length===0)return!1;await Fd.mkdir(tn.dirname(o),{recursive:!0});let c=a.length===0||a.endsWith(`
|
|
207
|
+
`)?"":`
|
|
208
|
+
`;return await Fd.appendFile(o,`${c}${s.join(`
|
|
209
|
+
`)}
|
|
210
|
+
`,"utf8"),!0}function XY(e,t,r){let n=tn.resolve(e,r??tn.join(".worktrees",t)),i=tn.resolve(e,te(e,["rev-parse","--git-common-dir"]));if(Wj(i,n))throw new Error("Native worktree path cannot be inside the Git common directory");if(Yt(e).some(o=>ye(o,n)))throw new Error(`Native worktree path is already registered: ${n}`);return n}async function ZY(e){try{throw await Fd.lstat(e),new Error(`Native worktree path already exists: ${e}`)}catch(t){if(t.code!=="ENOENT")throw t}}async function Bj(e){try{return await Fd.lstat(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function uR(e){let t=tn.resolve(e.projectRoot);if(e.isolation==="current"){if(e.changeBranch||e.targetBranch||e.worktreePath)throw new Error("Native current isolation does not accept --change-branch, --target-branch, or --worktree-path");let m=ue(t);if(m.isGitWorktree&&m.currentBranch===null)throw new Error("Native workspace binding requires a branch; detached HEAD is not supported");return{projectRoot:t,binding:{isolation:"current",changeBranch:m.currentBranch,targetBranch:m.currentBranch},preparation:{isolation:"current",projectRoot:t,changeBranch:m.currentBranch,targetBranch:m.currentBranch,worktreePath:null,createdBranch:!1,createdWorktree:!1,gitExcludeUpdated:!1,configInitialized:!1}}}let r=ue(t);if(!r.isGitWorktree||r.currentBranch===null||r.primaryWorktreeRoot===null||r.currentWorktreeRoot===null)throw new Error("Native branch and worktree isolation require an attached Git branch");let n=e.changeBranch??`comet/${e.name}`;Zy(t,n);let i=r.currentBranch===n,o=e.targetBranch??(i?void 0:r.currentBranch);if(!o)throw new Error("Native isolated workspace already on its change branch requires --target-branch");if(Zy(t,o),!Cu(t,o))throw new Error(`Native target branch is not a verified local branch: ${o}`);let a=await Dj(r.primaryWorktreeRoot);if(e.isolation==="branch"){if(e.worktreePath)throw new Error("--worktree-path is only valid with --isolation worktree");let m=!1;if(!i){if(!Vo(t))throw new Error("Native branch isolation requires a clean current working directory");if(Cu(t,n))throw new Error(`Native change branch already exists: ${n}`);te(t,["switch","-c",n,o]),m=!0}let h;try{h=await Jh(t,e.sourceConfig)}catch(g){throw new $i(`Native branch preparation is incomplete: ${g.message}`,{isolation:"branch",projectRoot:t,changeBranch:n,targetBranch:o,worktreePath:null,createdBranch:m,createdWorktree:!1,gitExcludeUpdated:a,configInitialized:!1},{cause:g})}return{projectRoot:t,binding:{isolation:"branch",changeBranch:n,targetBranch:o},preparation:{isolation:"branch",projectRoot:t,changeBranch:n,targetBranch:o,worktreePath:null,createdBranch:m,createdWorktree:!1,gitExcludeUpdated:a,configInitialized:h}}}if(i){if(!r.isSecondaryWorktree)throw new Error("Native worktree isolation must use a linked Git worktree");let m=e.worktreePath?tn.resolve(r.primaryWorktreeRoot,e.worktreePath):void 0;if(m&&!ye(m,r.currentWorktreeRoot))throw new Error(`Native worktree path ${m} does not match the current worktree ${r.currentWorktreeRoot}`);let h;try{h=await Jh(t,e.sourceConfig)}catch(g){throw new $i(`Native worktree preparation is incomplete: ${g.message}`,{isolation:"worktree",projectRoot:t,changeBranch:n,targetBranch:o,worktreePath:t,createdBranch:!1,createdWorktree:!1,gitExcludeUpdated:a,configInitialized:!1},{cause:g})}return{projectRoot:t,binding:{isolation:"worktree",changeBranch:n,targetBranch:o},preparation:{isolation:"worktree",projectRoot:t,changeBranch:n,targetBranch:o,worktreePath:t,createdBranch:!1,createdWorktree:!1,gitExcludeUpdated:a,configInitialized:h}}}let s=em(r.primaryWorktreeRoot),c=s.find(m=>m.branch===n);if(c&&await Bj(c.root)){let m=e.worktreePath?tn.resolve(r.primaryWorktreeRoot,e.worktreePath):void 0;if(m&&!ye(m,c.root))throw new Error(`Native worktree branch ${n} is already checked out at ${c.root}`);let h;try{h=await Jh(c.root,e.sourceConfig)}catch(g){throw new $i(`Native worktree preparation is incomplete: ${g.message}`,{isolation:"worktree",projectRoot:c.root,changeBranch:n,targetBranch:o,worktreePath:c.root,createdBranch:!1,createdWorktree:!1,gitExcludeUpdated:a,configInitialized:!1},{cause:g})}return{projectRoot:c.root,binding:{isolation:"worktree",changeBranch:n,targetBranch:o},preparation:{isolation:"worktree",projectRoot:c.root,changeBranch:n,targetBranch:o,worktreePath:c.root,createdBranch:!1,createdWorktree:!1,gitExcludeUpdated:a,configInitialized:h}}}c&&!await Bj(c.root)&&(te(r.primaryWorktreeRoot,["worktree","prune"]),s=em(r.primaryWorktreeRoot));let l=Cu(t,n);if(s.some(m=>m.branch===n))throw new Error(`Native change branch ${n} is already registered to a worktree`);let u=XY(r.primaryWorktreeRoot,e.name,e.worktreePath);await ZY(u);let f=await Dj(r.primaryWorktreeRoot,u),p={isolation:"worktree",projectRoot:u,changeBranch:n,targetBranch:o,worktreePath:u,createdBranch:!1,createdWorktree:!1,gitExcludeUpdated:a||f,configInitialized:!1};try{te(r.primaryWorktreeRoot,l?["worktree","add",u,n]:["worktree","add","-b",n,u,o]),p.createdBranch=!l,p.createdWorktree=!0,p.configInitialized=await Jh(u,e.sourceConfig)}catch(m){throw new $i(`Native worktree preparation is incomplete: ${m.message}`,p,{cause:m})}return{projectRoot:u,binding:{isolation:"worktree",changeBranch:n,targetBranch:o},preparation:p}}var qj=x(()=>{"use strict";tl();tl();Sr();it();Et();el()});import ks from"node:path";function Nt(e){if(!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(e))throw new Error(`Invalid Native Supervisor parent name: ${e}`);return`comet/supervisor/${e}/integration`}function It(e,t){if(!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(t))throw new Error(`Invalid Native Supervisor parent name: ${t}`);return aR(e,".worktrees",`${t}-integration`)}function zt(e,t,r){if(!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(t)||!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(r))throw new Error("Native Supervisor parent and child names are invalid");return aR(e,".worktrees",`${t}-${r}`)}async function zh(e){let t=ks.join(".worktrees",`${e.parent}-integration`);return uR({projectRoot:e.projectRoot,name:`${e.parent}-integration`,isolation:"worktree",changeBranch:Nt(e.parent),targetBranch:e.targetBranch,worktreePath:t,sourceConfig:e.sourceConfig})}async function Kh(e){if(!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(e.parent)||!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(e.child))throw new Error("Native Supervisor parent and child names are invalid");return uR({projectRoot:e.projectRoot,name:`${e.parent}-${e.child}`,isolation:"worktree",changeBranch:`comet/supervisor/${e.parent}/${e.child}`,targetBranch:e.targetBranch,worktreePath:ks.join(".worktrees",`${e.parent}-${e.child}`),sourceConfig:e.sourceConfig})}function fR(e,t){try{return te(e,["show-ref","--verify","--quiet",`refs/heads/${t}`]),!0}catch{return!1}}function e9(e,t){let r=ks.relative(ks.resolve(e),ks.resolve(t));return r===""||!ks.isAbsolute(r)&&!r.startsWith(`..${ks.sep}`)}function dR(e){if(ue(e.targetRoot).currentBranch!==e.targetBranch||pe(e.targetRoot,e.targetBranch)!==e.targetCommit)throw new Error("Native Supervisor target branch changed during cleanup")}function Hd(e){dR(e);let t=Yt(e.projectRoot);for(let r of e.candidates){if(t.some(n=>ye(n,r.root))){if(e9(r.root,process.cwd()))throw new Error(`Native Supervisor cannot clean the current worktree: ${r.root}`);if(ue(r.root).currentBranch!==r.branch||!ho(r.root))throw new Error(`Native Supervisor cleanup found a changed worktree: ${r.root}`)}if(fR(e.projectRoot,r.branch))try{te(e.projectRoot,["merge-base","--is-ancestor",r.branch,e.targetCommit])}catch{throw new Error(`Native Supervisor cleanup found an unintegrated branch: ${r.branch}`)}}}function rl(e){let t=Yt(e.projectRoot);return e.candidates.every(r=>!t.some(n=>ye(n,r.root))&&!fR(e.projectRoot,r.branch))}async function pR(e){if(!rl(e)){Hd(e);for(let t of e.candidates)dR(e),Yt(e.projectRoot).some(r=>ye(r,t.root))&&(await lR(t.root),te(e.projectRoot,["worktree","remove",t.root]));for(let t of e.candidates)dR(e),fR(e.projectRoot,t.branch)&&te(e.targetRoot,["branch","-d",t.branch]);if(!rl(e))throw new Error("Native Supervisor cleanup did not remove every temporary worktree")}}async function Lj(e,t){let r=await Dr(e,t.name,{diagnostics:!0});if(!r)return null;let n=ue(e.projectRoot).primaryWorktreeRoot??e.projectRoot,i=It(n,t.name),o=Nt(t.name);if(r.parent!==t.name||!ye(r.integration.worktree,i)||r.integration.branch!==o||!t.workspace.change_branch)throw new Error("Native Supervisor cleanup lacks its original parent workspace");let a=r.children.map(s=>{let c=s.projectRoot??s.task?.projectRoot??s.verification?.execution?.projectRoot,l=zt(n,t.name,s.name);if(!c||!ye(c,l)||!["integrated","archived"].includes(s.status))throw new Error("Native Supervisor cleanup requires its original integrated Child workspace: "+s.name);return{root:c,branch:"comet/supervisor/"+t.name+"/"+s.name}});return a.push({root:i,branch:o}),{projectRoot:e.projectRoot,targetRoot:e.projectRoot,targetBranch:t.workspace.change_branch,targetCommit:r.integration.headCommit,candidates:a}}var rn=x(()=>{"use strict";it();Oj();Sr();ai();Oi();el();qj()});function nl(e){return e.replaceAll(`\r
|
|
211
|
+
`,`
|
|
212
|
+
`).replaceAll("\r",`
|
|
213
|
+
`)}function Qj(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new xt(`${t} must be an object`);return e}function Uj(e,t,r){let n=Object.keys(e).filter(i=>!t.has(i));if(n.length>0)throw new xt(`${r} has unknown field(s): ${n.join(", ")}`)}function Jj(e,t){if(typeof e!="string"||e.trim().length===0)throw new xt(`${t} must be a non-empty string`);return e.trim()}function Vj(e,t){if(e!==void 0){if(typeof e!="string")throw new xt(`${t} must be text`);return nl(e).replace(/^\n+|\n+$/gu,"")}}function Mj(e,t){let r=Jj(e,t);if(!Hj.test(r))throw new xt(`${t} is not a valid stable requirement ID`);return r}function r9(e,t){let r=Jj(e,t);if(!t9.test(r))throw new xt(`${t} is not a valid capability ID`);return r}function n9(e,t){let r=`Native delta operations[${t}]`,n=Qj(e,r);Uj(n,new Set(["id","operation","to_id","title","body","expected_hash"]),r);let i=Mj(n.id,`${r}.id`),o=n.operation;if(!["add","modify","remove","rename"].includes(String(o)))throw new xt(`${r}.operation is invalid`);let a=o,s=n.to_id===void 0?void 0:Mj(n.to_id,`${r}.to_id`),c=Vj(n.title,`${r}.title`),l=Vj(n.body,`${r}.body`);if(a==="add"){if(s!==void 0||!l?.trim())throw new xt(`${r} add requires body and forbids to_id`)}else if(a==="modify"){if(s!==void 0||!l?.trim())throw new xt(`${r} modify requires body and forbids to_id`)}else if(a==="remove"){if(s!==void 0||c!==void 0||l!==void 0)throw new xt(`${r} remove forbids to_id, title, and body`)}else if(s===void 0||s===i||l==="")throw new xt(`${r} rename requires a different to_id`);return{id:i,operation:a,...s===void 0?{}:{to_id:s},...c===void 0?{}:{title:c},...l===void 0?{}:{body:l}}}function i9(e){let t=Qj(e,"Native delta");if(Uj(t,new Set(["schema","capability","base_hash","base_version","legacy_hash","base_requirements","independent_requirements","operations"]),"Native delta"),t.schema!==mR)throw new xt(`Native delta schema must be ${mR}`);let r=r9(t.capability,"Native delta capability");if(!Array.isArray(t.operations))throw new xt("Native delta operations must be an array");let n=t.operations.map(n9),i=new Set;for(let[o,a]of n.entries()){let s=[a.id,...a.to_id===void 0?[]:[a.to_id]];for(let c of s){if(i.has(c))throw new xt(`Native delta operations contain duplicate or overlapping requirement ID ${c} at ${o}`);i.add(c)}}return{schema:mR,capability:r,base_version:Number.isSafeInteger(t.base_version)&&Number(t.base_version)>0?Number(t.base_version):1,operations:n}}function o9(e){let t=(0,gR.parseDocument)(e,{uniqueKeys:!0});if(t.errors.length>0)throw new xt(`Native delta is invalid YAML: ${t.errors[0].message}`);return t.toJS({mapAsMap:!1})}function nn(e){return i9(typeof e=="string"?o9(e):e)}function a9(e){let t=/^\s{0,3}(#{1,6})\s+/u.exec(e);return t?t[1].length:null}function s9(e){let t=[],r=null;for(let[n,i]of e.entries()){let o=/^\s{0,3}(`{3,}|~{3,})(.*)$/u.exec(i.trimEnd());if(o){r?o[1][0]===r.marker&&o[1].length>=r.length&&o[2].trim().length===0&&(r=null):r={marker:o[1][0],length:o[1].length};continue}if(r)continue;let a=/^(\s{0,3})(#{2,6})\s+Requirement:\s*([^\s]+)(?:\s+(.*?))?\s*$/u.exec(i);if(!a)continue;let s=a[3];if(!Hj.test(s))throw new xt(`Native total Spec requirement ID is invalid: ${s}`);t.push({line:n,level:a[2].length,id:s,title:a[4]?.trim()??""})}return t}function Gh(e){let t=nl(e),r=t.split(`
|
|
214
|
+
`),n=s9(r),i=[],o=new Set;for(let l of n){if(o.has(l.id))throw new xt(`Native total Spec contains duplicate requirement ID ${l.id}`);o.add(l.id);let u=r.length;for(let f=l.line+1;f<r.length;f+=1){if(n.some(p=>p.line===f)){u=f;break}let d=a9(r[f]);if(d!==null&&d<=l.level){u=f;break}}i.push({start:l.line,end:u,marker:l})}let a=new Map;for(let l of i){let u=`${r.slice(l.start,l.end).join(`
|
|
215
|
+
`)}${l.end<r.length?`
|
|
216
|
+
`:""}`,f=r.slice(l.start+1,l.end).join(`
|
|
217
|
+
`).replace(/^\n/u,"").replace(/\n+$/u,"");a.set(l.marker.id,{id:l.marker.id,level:l.marker.level,title:l.marker.title,body:f,raw:u,startLine:l.start,endLine:l.end})}let s=[],c=0;for(let l of i)s.push(r.slice(c,l.start).join(`
|
|
218
|
+
`)),c=l.end;return s.push(r.slice(c).join(`
|
|
219
|
+
`)),{text:t,lines:r,requirements:a,legacyText:s.join(`
|
|
220
|
+
`)}}function Yh(e,t,r,n){let i=`${"#".repeat(e)} Requirement: ${t}${r?.trim()?` ${r.trim()}`:""}`,o=nl(n).replace(/\n+$/u,"");return[i,"",...o.split(`
|
|
221
|
+
`),"",""].join(`
|
|
222
|
+
`)}function hR(e){return e.operation==="rename"?[e.id,e.to_id]:[e.id]}function Xh(e,t){if(e.operation==="rename"){if(!t)throw new xt(`Rename target does not exist: ${e.id}`);return{id:e.to_id,level:t.level,title:e.title??t.title,body:e.body??t.body}}return{id:e.id,level:t?.level??2,title:e.title??t?.title,body:e.body??t?.body??""}}function c9(e,t,r){let n=Gh(e),i=[...n.lines],o=n.requirements.get(t.id);if(!o)throw new xt(`Requirement target disappeared: ${t.id}`);return i.splice(o.startLine,o.endLine-o.startLine,...r.split(`
|
|
223
|
+
`)),i.join(`
|
|
224
|
+
`)}function l9(e,t){let r=nl(e),n=r.length===0||r.endsWith(`
|
|
225
|
+
|
|
226
|
+
`)?"":`
|
|
227
|
+
`,i=`${r}${n}`;return`${i.endsWith(`
|
|
228
|
+
`)||i.length===0?i:`${i}
|
|
229
|
+
`}${t}`}function u9(e,t){if(e.operation==="add"||e.operation==="modify"){let o=t.requirements.get(e.id);if(!o)return!1;let a=Xh(e,e.operation==="modify"?o:void 0);return o.raw===Yh(a.level,a.id,a.title,a.body)}if(e.operation==="remove")return!1;let r=t.requirements.get(e.to_id),n=t.requirements.get(e.id);if(!r||n)return!1;let i=Xh(e,{id:e.id,level:r.level,title:r.title,body:r.body,raw:r.raw,startLine:r.startLine,endLine:r.endLine});return r.raw===Yh(i.level,i.id,i.title,i.body)}function zj(e){let t=nl(e.baselineMarkdown),r=[],n=[];for(let o of e.delta.operations){let a=Gh(t),s=a.requirements.get(o.id);if(e.allowAlreadyApplied&&u9(o,a)){n.push({id:o.id,operation:o.operation,status:"already-applied",targetIds:hR(o)});continue}if(o.operation==="add"){if(s)throw new Qd([o.id],`Native delta add conflicts with existing requirement ${o.id}`);let c=Xh(o,void 0);t=l9(t,Yh(c.level,c.id,c.title,c.body))}else{if(!s)throw new Qd([o.id],`Native delta ${o.operation} target does not exist: ${o.id}`);let c=Xh(o,s);if(o.operation==="rename"&&Gh(t).requirements.has(o.to_id))throw new Qd([o.id,o.to_id],`Native delta rename destination already exists: ${o.to_id}`);if(o.operation==="remove"){let l=[...Gh(t).lines];l.splice(s.startLine,s.endLine-s.startLine),t=l.join(`
|
|
230
|
+
`)}else t=c9(t,s,Yh(c.level,c.id,c.title,c.body))}r.push(...hR(o)),n.push({id:o.id,operation:o.operation,status:"changed",targetIds:hR(o)})}return{markdown:nl(t),rebased:e.rebased,changedRequirementIds:[...new Set(r)],operationResults:n}}function Kj(e){return zj({baselineMarkdown:e.baselineMarkdown,delta:nn(e.delta),allowAlreadyApplied:e.allowAlreadyApplied??!1,rebased:!1})}function Ud(e){return zj({baselineMarkdown:e.currentMarkdown,delta:nn(e.delta),allowAlreadyApplied:!0,rebased:!1})}var gR,mR,Fj,t9,Hj,xt,Qd,il=x(()=>{"use strict";gR=dr(Ur(),1),mR="comet.native.delta.v1",Fj="delta.yaml",t9=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,Hj=/^[a-z][a-z0-9]*(?:[._-][a-z0-9]+)*$/u,xt=class extends Error{code="native-delta-invalid";constructor(t){super(t),this.name="NativeDeltaValidationError"}},Qd=class extends Error{code="native-delta-conflict";conflictIds;constructor(t,r){super(r),this.name="NativeDeltaConflictError",this.conflictIds=[...new Set(t)]}}});var si,Di,Bi,ol,al,Jd,zd=x(()=>{"use strict";si="comet.native.v3",Di="comet.native.v2",Bi="comet.native.v1",ol="comet.native.transition.v3",al="comet.native.transition.v2",Jd="comet.native.transition.v1"});import d9 from"node:path";function Gd(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be a mapping`);return e}function Zj(e,t,r){let n=Object.keys(e).filter(i=>!t.has(i));if(n.length>0)throw new Error(`${r} has unknown field(s): ${n.join(", ")}`)}function sl(e){if(!Xj.test(e))throw new Error(`Invalid Native change name: ${e}`)}function Zh(e){if(!Xj.test(e))throw new Error(`Invalid Native capability id: ${e}`)}function e0(e,t){if(e.length===0||d9.isAbsolute(e)||/^(?:[A-Za-z]:|~|[\\/])/u.test(e)||e.split(/[\\/]/u).includes(".."))throw new Error(`${t} must stay inside the Native change`)}function y9(e,t){let r=Gd(e,`spec_changes[${t}]`);if(Zj(r,m9,`spec_changes[${t}]`),typeof r.capability!="string")throw new Error("spec change capability is required");if(Zh(r.capability),r.operation!=="create"&&r.operation!=="replace"&&r.operation!=="remove")throw new Error(`Invalid spec operation for ${r.capability}`);let n=r.source,i=r.base_hash;if(n!==void 0&&typeof n!="string")throw new Error(`Spec source for ${r.capability} must be a string`);if(typeof n=="string"&&e0(n,`Spec source for ${r.capability}`),r.operation==="create"){if(!n)throw new Error(`Create spec ${r.capability} requires source`);if(i!==null)throw new Error(`Create spec ${r.capability} requires null base_hash`)}else if(r.operation==="replace"){if(!n)throw new Error(`Replace spec ${r.capability} requires source`);if(typeof i!="string"||!wR.test(i))throw new Error(`Replace spec ${r.capability} requires a SHA-256 base_hash`)}else{if(n!==void 0)throw new Error(`Remove spec ${r.capability} forbids source`);if(typeof i!="string"||!wR.test(i))throw new Error(`Remove spec ${r.capability} requires a SHA-256 base_hash`)}return{capability:r.capability,operation:r.operation,...typeof n=="string"?{source:n}:{},base_hash:i}}function k9(e){return/^\d{4}-\d{2}-\d{2}$/u.test(e)?new Date(`${e}T00:00:00.000Z`).toISOString().slice(0,10)===e:!1}function yR(e,t){if(Zj(e,t,Vn),typeof e.name!="string")throw new Error("Native change name is required");if(sl(e.name),e.language!=="en"&&e.language!=="zh-CN")throw new Error("Native change language must be en or zh-CN");if(typeof e.phase!="string"||!h9.has(e.phase))throw new Error("Native change phase is invalid");if(e.brief!=="brief.md")throw new Error("Native change brief must be brief.md");if(e.approval!==null&&!g9.has(e.approval))throw new Error("Native change approval is invalid");if(!Array.isArray(e.spec_changes))throw new Error("Native spec_changes must be an array");let r=e.spec_changes.map(y9),n=r.map(i=>i.capability).filter((i,o,a)=>a.indexOf(i)!==o);if(n.length>0)throw new Error(`Duplicate Native capability operation: ${[...new Set(n)].join(", ")}`);if(typeof e.verification_result!="string"||!v9.has(e.verification_result))throw new Error("Native verification_result is invalid");if(e.verification_report!==null&&typeof e.verification_report!="string")throw new Error("Native verification_report must be a string or null");if(typeof e.verification_report=="string"&&e0(e.verification_report,"Native verification_report"),typeof e.archived!="boolean")throw new Error("Native archived must be boolean");if(typeof e.created_at!="string"||!k9(e.created_at))throw new Error("Native created_at must be a valid YYYY-MM-DD date");if(e.run_id!==null&&(typeof e.run_id!="string"||e.run_id.length===0))throw new Error("Native run_id must be a non-empty string or null");return{name:e.name,language:e.language,phase:e.phase,brief:"brief.md",approval:e.approval,spec_changes:r,verification_result:e.verification_result,verification_report:e.verification_report,archived:e.archived,created_at:e.created_at,run_id:e.run_id}}function pa(e){let t=Gd(e,Vn);if(t.schema!==Bi)throw new Error(`Expected ${Bi}`);return{schema:Bi,...yR(t,f9)}}function Kd(e,t){if(!Number.isSafeInteger(e)||e<1)throw new Error(`${t} must be a positive integer`);return e}function vR(e,t,r){if(e===null)return null;let n=typeof e=="string"?w9.exec(e):null;if(!n||n[1]!==r)throw new Error(`${t} must be null or runtime/evidence/${r}/<sha256>.json relative to the Native change`);return e}function b9(e){if(e==null)return null;if(typeof e!="string"||!wR.test(e))throw new Error("Native approved_contract_hash must be null or a SHA-256 hash");return e}function A9(e){if(e===void 0)return"legacy-v1";if(e!=="legacy-v1")throw new Error("Native verification_protocol must be legacy-v1");return e}function ma(e){let t=Gd(e,Vn);if(t.schema!==Di)throw new Error(`Expected ${Di}`);if(Kd(t.minimum_runtime_version,"Native v2 minimum_runtime_version")!==2)throw new Error(`Native ${Di} minimum_runtime_version must be 2`);return{schema:Di,minimum_runtime_version:2,revision:Kd(t.revision,"Native v2 revision"),...yR(t,Yj)}}function li(e){let t=Gd(e,Vn);if(t.schema!==si){if(t.schema===Bi||t.schema===Di){let a=t.schema===Bi?pa(t):ma(t);throw new bs(a.name,a.schema)}throw new ci(typeof t.schema=="string"?t.schema:"(missing)",typeof t.minimum_runtime_version=="number"?t.minimum_runtime_version:null)}let r=Kd(t.minimum_runtime_version,"Native minimum_runtime_version");if(r>3)throw new ci(t.schema,r);if(r!==3)throw new Error(`Native ${t.schema} minimum_runtime_version must be ${3}`);let n=Kd(t.revision,"Native revision"),i=yR(t,p9),o=b9(t.approved_contract_hash);if(i.approval===null&&o!==null)throw new Error("Native approved_contract_hash requires an approval");return{schema:si,minimum_runtime_version:3,revision:n,verification_protocol:A9(t.verification_protocol),...i,approved_contract_hash:o,implementation_scope:vR(t.implementation_scope,"Native implementation_scope","scopes"),verification_evidence:vR(t.verification_evidence,"Native verification_evidence","verifications"),partial_allowance:vR(t.partial_allowance,"Native partial_allowance","allowances")}}function eg(e){let t=Gd(e,Vn);if(t.schema===Bi){let i=pa(t);return{status:"migration-required",schema:i.schema,minimumRuntimeVersion:1,state:i,message:`Native change ${i.name} requires migration to ${si}`}}if(t.schema===Di){let i=ma(t);return{status:"migration-required",schema:i.schema,minimumRuntimeVersion:i.minimum_runtime_version,state:i,message:`Native change ${i.name} requires migration to ${si}`}}if(t.schema!==si){let i=typeof t.minimum_runtime_version=="number"&&Number.isSafeInteger(t.minimum_runtime_version)?t.minimum_runtime_version:null;return{status:"runtime-incompatible",schema:typeof t.schema=="string"?t.schema:"(missing)",minimumRuntimeVersion:i,state:null,message:new ci(typeof t.schema=="string"?t.schema:"(missing)",i).message}}let r=Kd(t.minimum_runtime_version,"Native minimum_runtime_version");if(r>3)return{status:"runtime-incompatible",schema:t.schema,minimumRuntimeVersion:r,state:null,message:new ci(t.schema,r).message};let n=li(t);return{status:"current",schema:n.schema,minimumRuntimeVersion:n.minimum_runtime_version,state:n}}function Yd(e){let t=li(e);return{schema:t.schema,minimum_runtime_version:t.minimum_runtime_version,revision:t.revision,verification_protocol:t.verification_protocol,name:t.name,language:t.language,phase:t.phase,brief:t.brief,approval:t.approval,approved_contract_hash:t.approved_contract_hash??null,spec_changes:t.spec_changes.map(r=>({capability:r.capability,operation:r.operation,...r.source?{source:r.source}:{},base_hash:r.base_hash})),verification_result:t.verification_result,verification_report:t.verification_report,implementation_scope:t.implementation_scope,verification_evidence:t.verification_evidence,partial_allowance:t.partial_allowance,archived:t.archived,created_at:t.created_at,run_id:t.run_id}}var Gj,f9,Yj,p9,m9,h9,g9,v9,Vn,wR,Xj,w9,bs,ci,Xd=x(()=>{"use strict";zd();Gj=["schema","name","language","phase","brief","approval","spec_changes","verification_result","verification_report","archived","created_at","run_id"],f9=new Set(Gj),Yj=new Set([...Gj,"minimum_runtime_version","revision"]),p9=new Set([...Yj,"approved_contract_hash","implementation_scope","verification_evidence","partial_allowance","verification_protocol"]),m9=new Set(["capability","operation","source","base_hash"]),h9=new Set(["shape","build","verify","archive"]),g9=new Set(["implicit","confirmed"]),v9=new Set(["pending","pass","fail"]),Vn="comet-state.yaml",wR=/^[a-f0-9]{64}$/u,Xj=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,w9=/^runtime\/evidence\/(scopes|allowances|verifications)\/([a-f0-9]{64})\.json$/u,bs=class extends Error{constructor(r,n){super(`Native change ${r} uses ${n}; run comet native doctor ${r} --repair before mutating it`);this.change=r;this.schema=n;this.name="NativeSchemaMigrationRequiredError"}change;schema;code="native-schema-migration-required"},ci=class extends Error{constructor(r,n){super(r!==si||n===null?`Unsupported Native change schema ${r} for runtime protocol ${3}`:`Native change ${r} requires runtime protocol ${n}; current protocol is ${3}`);this.schema=r;this.minimumRuntimeVersion=n;this.name="NativeRuntimeCompatibilityError"}schema;minimumRuntimeVersion;code="native-runtime-incompatible"}});function RR(){return{async:!1,breaks:!1,extensions:null,gfm:!0,hooks:null,pedantic:!1,renderer:null,silent:!1,tokenizer:null,walkTokens:null}}function c0(e){Ns=e}function cl(e){let t=[];return r=>{let n=Math.max(0,Math.min(3,r-1)),i=t[n];return i||(i=e(n),t[n]=i),i}}function Ie(e,t=""){let r=typeof e=="string"?e:e.source,n={replace:(i,o)=>{let a=typeof o=="string"?o:o.source;return a=a.replace(yr.caret,"$1"),r=r.replace(i,a),n},getRegex:()=>new RegExp(r,t)};return n}function Wi(e,t){if(t){if(yr.escapeTest.test(e))return e.replace(yr.escapeReplace,n0)}else if(yr.escapeTestNoEncode.test(e))return e.replace(yr.escapeReplaceNoEncode,n0);return e}function i0(e){try{e=encodeURI(e).replace(yr.percentDecode,"%")}catch{return null}return e}function o0(e,t){let r=e.replace(yr.findPipe,(o,a,s)=>{let c=!1,l=a;for(;--l>=0&&s[l]==="\\";)c=!c;return c?"|":" |"}),n=r.split(yr.splitPipe),i=0;if(n[0].trim()||n.shift(),n.length>0&&!n.at(-1)?.trim()&&n.pop(),t)if(n.length>t)n.splice(t);else for(;n.length<t;)n.push("");for(;i<n.length;i++)n[i]=n[i].trim().replace(yr.slashPipe,"|");return n}function ha(e,t,r){let n=e.length;if(n===0)return"";let i=0;for(;i<n;){let o=e.charAt(n-i-1);if(o===t&&!r)i++;else if(o!==t&&r)i++;else break}return e.slice(0,n-i)}function a0(e){let t=e.split(`
|
|
231
|
+
`),r=t.length-1;for(;r>=0&&yr.blankLine.test(t[r]);)r--;return t.length-r<=2?e:t.slice(0,r+1).join(`
|
|
232
|
+
`)}function h6(e,t){if(e.indexOf(t[1])===-1)return-1;let r=0;for(let n=0;n<e.length;n++)if(e[n]==="\\")n++;else if(e[n]===t[0])r++;else if(e[n]===t[1]&&(r--,r<0))return n;return r>0?-2:-1}function g6(e,t=0){let r=t,n="";for(let i of e)if(i===" "){let o=4-r%4;n+=" ".repeat(o),r+=o}else n+=i,r++;return n}function s0(e,t,r,n,i){let o=t.href,a=t.title||null,s=e[1].replace(i.other.outputLinkReplace,"$1"),c=e[0].charAt(0)==="!";n.state.inLink=!0;let l=n.state.linkEmitted,u=n.state.inRawBlock;n.state.linkEmitted=!1;let f=n.inlineTokens(s),d=n.state.linkEmitted;if(n.state.linkEmitted=l,n.state.inLink=!1,!c){if(d){n.state.inRawBlock=u;return}n.state.linkEmitted=!0}return{type:c?"image":"link",raw:r,href:o,title:a,text:s,tokens:f}}function v6(e,t,r){let n=e.match(r.other.indentCodeCompensation);if(n===null)return t;let i=n[1];return t.split(`
|
|
233
|
+
`).map(o=>{let a=o.match(r.other.beginningSpace);if(a===null)return o;let[s]=a;return s.length>=i.length?o.slice(i.length):o}).join(`
|
|
234
|
+
`)}function tt(e,t){return Rs.parse(e,t)}function y6(...e){return Rs.use(...e),tt.defaults=Rs.defaults,c0(tt.defaults),tt}var Ns,As,R9,yr,N9,S9,E9,tf,C9,NR,l0,u0,_9,SR,I9,ER,x9,P9,og,CR,T9,d0,O9,j9,$9,_R,t0,D9,B9,W9,q9,f0,L9,go,ll,rf,V9,M9,p0,F9,H9,Q9,m0,U9,J9,z9,K9,h0,G9,Y9,X9,Z9,e6,t6,r6,n6,i6,o6,a6,s6,c6,l6,rg,u6,g0,v0,d6,r0,IR,f6,kR,p6,tg,Zd,m6,n0,ng,Wr,ig,xR,ui,ef,w6,Rs,fse,pse,w0,mse,hse,gse,PR=x(()=>{"use strict";Ns=RR();As={exec:()=>null};R9=((e="")=>{try{return!!new RegExp("(?<=1)(?<!1)"+e)}catch{return!1}})(),yr={codeRemoveIndent:/^(?: {1,4}| {0,3}\t)/gm,outputLinkReplace:/\\([\[\]])/g,indentCodeCompensation:/^(\s+)(?:```)/,beginningSpace:/^\s+/,endingHash:/#$/,startingSpaceChar:/^ /,endingSpaceChar:/ $/,nonSpaceChar:/[^ ]/,newLineCharGlobal:/\n/g,tabCharGlobal:/\t/g,multipleSpaceGlobal:/\s+/g,blankLine:/^[ \t]*$/,doubleBlankLine:/\n[ \t]*\n[ \t]*$/,blockquoteStart:/^ {0,3}>/,blockquoteSetextReplace:/\n {0,3}((?:=+|-+) *)(?=\n|$)/g,blockquoteSetextReplace2:/^ {0,3}>[ \t]?/gm,listReplaceNesting:/^ {1,4}(?=( {4})*[^ ])/g,listIsTask:/^\[[ xX]\] +\S/,listReplaceTask:/^\[[ xX]\] +/,listTaskCheckbox:/\[[ xX]\]/,anyLine:/\n.*\n/,hrefBrackets:/^<(.*)>$/,tableDelimiter:/[:|]/,tableAlignChars:/^\||\| *$/g,tableRowBlankLine:/\n[ \t]*$/,tableAlignRight:/^ *-+: *$/,tableAlignCenter:/^ *:-+: *$/,tableAlignLeft:/^ *:-+ *$/,startATag:/^<a /i,endATag:/^<\/a>/i,startPreScriptTag:/^<(pre|code|kbd|script)(\s|>)/i,endPreScriptTag:/^<\/(pre|code|kbd|script)(\s|>)/i,startAngleBracket:/^</,endAngleBracket:/>$/,pedanticHrefTitle:/^([^'"]*[^\s])\s+(['"])(.*)\2/,unicodeAlphaNumeric:/[\p{L}\p{N}]/u,escapeTest:/[&<>"']/,escapeReplace:/[&<>"']/g,escapeTestNoEncode:/[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/,escapeReplaceNoEncode:/[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/g,caret:/(^|[^\[])\^/g,percentDecode:/%25/g,findPipe:/\|/g,splitPipe:/ \|/,slashPipe:/\\\|/g,carriageReturn:/\r\n|\r/g,spaceLine:/^ +$/gm,notSpaceStart:/^\S*/,endingNewline:/\n$/,listItemRegex:e=>new RegExp(`^( {0,3}${e})((?:[ ][^\\n]*)?(?:\\n|$))`),nextBulletRegex:cl(e=>new RegExp(`^ {0,${e}}(?:[*+-]|\\d{1,9}[.)])((?:[ ][^\\n]*)?(?:\\n|$))`)),hrRegex:cl(e=>new RegExp(`^ {0,${e}}((?:- *){3,}|(?:_ *){3,}|(?:\\* *){3,})(?:\\n+|$)`)),fencesBeginRegex:cl(e=>new RegExp(`^ {0,${e}}(?:\`\`\`|~~~)`)),headingBeginRegex:cl(e=>new RegExp(`^ {0,${e}}#`)),htmlBeginRegex:cl(e=>new RegExp(`^ {0,${e}}<(?:[a-z].*>|!--)`,"i")),blockquoteBeginRegex:cl(e=>new RegExp(`^ {0,${e}}>`))},N9=/^(?:[ \t]*(?:\n|$))+/,S9=/^((?: {4}| {0,3}\t)[^\n]+(?:\n(?:[ \t]*(?:\n|$))*)?)+/,E9=/^ {0,3}(`{3,}(?=[^`\n]*(?:\n|$))|~{3,})([^\n]*)(?:\n|$)(?:|([\s\S]*?)(?:\n|$))(?: {0,3}\1[~`]* *(?=\n|$)|$)/,tf=/^ {0,3}((?:-[\t ]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})(?:\n+|$)/,C9=/^ {0,3}(#{1,6})(?=\s|$)(.*)(?:\n+|$)/,NR=/ {0,3}(?:[*+-]|\d{1,9}[.)])/,l0=/^(?!bull |blockCode|fences|blockquote|heading|html|table)((?:.|\n(?!\s*?\n|bull |blockCode|fences|blockquote|heading|html|table))+?)\n {0,3}(=+|-+) *(?:\n+|$)/,u0=Ie(l0).replace(/bull/g,NR).replace(/blockCode/g,/(?: {4}| {0,3}\t)/).replace(/fences/g,/ {0,3}(?:`{3,}|~{3,})/).replace(/blockquote/g,/ {0,3}>/).replace(/heading/g,/ {0,3}#{1,6}(?:\s|$)/).replace(/html/g,/ {0,3}<[^\n>]+>\n/).replace(/\|table/g,"").getRegex(),_9=Ie(l0).replace(/bull/g,NR).replace(/blockCode/g,/(?: {4}| {0,3}\t)/).replace(/fences/g,/ {0,3}(?:`{3,}|~{3,})/).replace(/blockquote/g,/ {0,3}>/).replace(/heading/g,/ {0,3}#{1,6}(?:\s|$)/).replace(/html/g,/ {0,3}<[^\n>]+>\n/).replace(/table/g,/ {0,3}\|?(?:[:\- ]*\|)+[\:\- ]*\n/).getRegex(),SR=/^([^\n]+(?:\n(?!hr|heading|lheading|blockquote|fences|list|html|table|[ \t]+\n)[^\n]+)*)/,I9=/^[^\n]+/,ER=/(?!\s*\])(?:\\[\s\S]|[^\[\]\\])+/,x9=Ie(/^ {0,3}\[(label)\]: *(?:\n[ \t]*)?([^<\s][^\s]*|<.*?>)(?:(?: +(?:\n[ \t]*)?| *\n[ \t]*)(title))? *(?:\n+|$)/).replace("label",ER).replace("title",/(?:"(?:\\"?|[^"\\])*"|'[^'\n]*(?:\n[^'\n]+)*\n?'|\([^()]*\))/).getRegex(),P9=Ie(/^(bull)([ \t][^\n]*?)?(?:\n|$)/).replace(/bull/g,NR).getRegex(),og="address|article|aside|base|basefont|blockquote|body|caption|center|col|colgroup|dd|details|dialog|dir|div|dl|dt|fieldset|figcaption|figure|footer|form|frame|frameset|h[1-6]|head|header|hr|html|iframe|legend|li|link|main|menu|menuitem|meta|nav|noframes|ol|optgroup|option|p|param|search|section|summary|table|tbody|td|tfoot|th|thead|title|tr|track|ul",CR=/<!--(?:-?>|[\s\S]*?(?:-->|$))/,T9=Ie("^ {0,3}(?:<(script|pre|style|textarea)[\\s>][\\s\\S]*?(?:</\\1>[^\\n]*\\n*|$)|comment[^\\n]*(\\n+|$)|<\\?[\\s\\S]*?(?:\\?>[^\\n]*\\n*|$)|<![A-Z][\\s\\S]*?(?:>[^\\n]*\\n*|$)|<!\\[CDATA\\[[\\s\\S]*?(?:\\]\\]>[^\\n]*\\n*|$)|</?(tag)(?: +|\\n|/?>)[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$)|<(?!script|pre|style|textarea)([a-z][\\w-]*)(?:attribute)*? */?>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$)|</(?!script|pre|style|textarea)[a-z][\\w-]*\\s*>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$))","i").replace("comment",CR).replace("tag",og).replace("attribute",/ +[a-zA-Z:_][\w.:-]*(?: *= *"[^"\n]*"| *= *'[^'\n]*'| *= *[^\s"'=<>`]+)?/).getRegex(),d0=e=>Ie(SR).replace("hr",tf).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("|table","").replace("blockquote"," {0,3}>").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*(?:\\n|$))|~~~)[^\\n]*(?:\\n|$)").replace("list",e).replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",og).getRegex(),O9=d0(/ {0,3}(?:[*+-]|1[.)])[ \t]+[^ \t\n]/),j9=d0(/ {0,3}(?:[*+-]|\d{1,9}[.)])(?:[ \t]|\n|$)/),$9=Ie(/^( {0,3}> ?(paragraph|[^\n]*)(?:\n|$))+/).replace("paragraph",j9).getRegex(),_R={blockquote:$9,code:S9,def:x9,fences:E9,heading:C9,hr:tf,html:T9,lheading:u0,list:P9,newline:N9,paragraph:O9,table:As,text:I9},t0=Ie("^ *([^\\n ].*)\\n {0,3}((?:\\| *)?:?-+:? *(?:\\| *:?-+:? *)*(?:\\| *)?)(?:\\n((?:(?! *\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\n|$))*)\\n*|$)").replace("hr",tf).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("blockquote"," {0,3}>").replace("code","(?: {4}| {0,3} )[^\\n]").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*(?:\\n|$))|~~~)[^\\n]*(?:\\n|$)").replace("list"," {0,3}(?:[*+-]|1[.)])[ \\t]").replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",og).getRegex(),D9={..._R,lheading:_9,table:t0,paragraph:Ie(SR).replace("hr",tf).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("table",t0).replace("blockquote"," {0,3}>").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*(?:\\n|$))|~~~)[^\\n]*(?:\\n|$)").replace("list"," {0,3}(?:[*+-]|1[.)])[ \\t]+[^ \\t\\n]").replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",og).getRegex()},B9={..._R,html:Ie(`^ *(?:comment *(?:\\n|\\s*$)|<(tag)[\\s\\S]+?</\\1> *(?:\\n{2,}|\\s*$)|<tag(?:"[^"]*"|'[^']*'|\\s[^'"/>\\s]*)*?/?> *(?:\\n{2,}|\\s*$))`).replace("comment",CR).replace(/tag/g,"(?!(?:a|em|strong|small|s|cite|q|dfn|abbr|data|time|code|var|samp|kbd|sub|sup|i|b|u|mark|ruby|rt|rp|bdi|bdo|span|br|wbr|ins|del|img)\\b)\\w+(?!:|[^\\w\\s@]*@)\\b").getRegex(),def:/^ *\[([^\]]+)\]: *<?([^\s>]+)>?(?: +(["(][^\n]+[")]))? *(?:\n+|$)/,heading:/^(#{1,6})(.*)(?:\n+|$)/,fences:As,lheading:/^(.+?)\n {0,3}(=+|-+) *(?:\n+|$)/,paragraph:Ie(SR).replace("hr",tf).replace("heading",` *#{1,6} *[^
|
|
235
|
+
]`).replace("lheading",u0).replace("|table","").replace("blockquote"," {0,3}>").replace("|fences","").replace("|list","").replace("|html","").replace("|tag","").getRegex()},W9=/^\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/,q9=/^(`+)([^`]|[^`][\s\S]*?[^`])\1(?!`)/,f0=/^( {2,}|\\)\n(?!\s*$)/,L9=/^(`+|[^`])(?:(?= {2,}\n)|[\s\S]*?(?:(?=[\\<!\[`*_]|\b_|$)|[^ ](?= {2,}\n)))/,go=/[\p{P}\p{S}]/u,ll=/[\s\p{P}\p{S}]/u,rf=/[^\s\p{P}\p{S}]/u,V9=Ie(/^((?![*_])punctSpace)/,"u").replace(/punctSpace/g,ll).getRegex(),M9=/[\p{Pi}\p{Ps}"']/u,p0=/(?!~)[\p{P}\p{S}]/u,F9=/(?!~)[\s\p{P}\p{S}]/u,H9=/(?:[^\s\p{P}\p{S}]|~)/u,Q9=Ie(/link|precode-code|html/,"g").replace("link",/\[(?:[^\[\]`]|(?<a>`+)[^`]+\k<a>(?!`))*?\]\((?:\\[\s\S]|[^\\\(\)]|\((?:\\[\s\S]|[^\\\(\)])*\))*\)/).replace("precode-",R9?"(?<!`)()":"(^^|[^`])").replace("code",/(?<b>`+)[^`]+\k<b>(?!`)/).replace("html",/<(?! )[^<>]*?>/).getRegex(),m0=/^(?:\*+(?:((?!\*)punct)|([^\s*]))?)|^_+(?:((?!_)punct)|([^\s_]))?/,U9=Ie(m0,"u").replace(/punct/g,go).getRegex(),J9=Ie(m0,"u").replace(/punct/g,p0).getRegex(),z9=/^(?:\*+(?:((?!\*)(?!openQuote)punct)|([^\s*]))?)|^_+(?:((?!_)(?!openQuote)punct)|([^\s_]))?/,K9=Ie(z9,"u").replace(/openQuote/g,M9).replace(/punct/g,go).getRegex(),h0="^[^_*]*?__[^_*]*?\\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\\*)punct(\\*+)(?=[\\s]|$)|notPunctSpace(\\*+)(?!\\*)(?=punctSpace|$)|(?!\\*)punctSpace(\\*+)(?=notPunctSpace)|[\\s](\\*+)(?!\\*)(?=punct)|(?!\\*)punct(\\*+)(?!\\*)(?=punct)|notPunctSpace(\\*+)(?=notPunctSpace)",G9=Ie(h0,"gu").replace(/notPunctSpace/g,rf).replace(/punctSpace/g,ll).replace(/punct/g,go).getRegex(),Y9=Ie(h0,"gu").replace(/notPunctSpace/g,H9).replace(/punctSpace/g,F9).replace(/punct/g,p0).getRegex(),X9="^[^_*]*?__[^_*]*?\\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\\*)punct(\\*+)(?=[\\s]|$)|notPunctSpace(\\*+)(?!\\*)(?=punctSpace|$)|(?!\\*)[\\s](\\*+)(?=notPunctSpace)|[\\s](\\*+)(?!\\*)(?=punct)|(?!\\*)punct(\\*+)(?!\\*)(?=punct)|(?:(?!\\*)punct|notPunctSpace)(\\*+)(?!\\*)(?=notPunctSpace)",Z9=Ie(X9,"gu").replace(/notPunctSpace/g,rf).replace(/punctSpace/g,ll).replace(/punct/g,go).getRegex(),e6=Ie("^[^_*]*?\\*\\*[^_*]*?_[^_*]*?(?=\\*\\*)|[^_]+(?=[^_])|(?!_)punct(_+)(?=[\\s]|$)|notPunctSpace(_+)(?!_)(?=punctSpace|$)|(?!_)punctSpace(_+)(?=notPunctSpace)|[\\s](_+)(?!_)(?=punct)|(?!_)punct(_+)(?!_)(?=punct)","gu").replace(/notPunctSpace/g,rf).replace(/punctSpace/g,ll).replace(/punct/g,go).getRegex(),t6="^[^_*]*?\\*\\*[^_*]*?_[^_*]*?(?=\\*\\*)|[^_]+(?=[^_])|(?!_)punct(_+)(?=[\\s]|$)|notPunctSpace(_+)(?!_)(?=punctSpace|$)|(?!_)[\\s](_+)(?=notPunctSpace)|[\\s](_+)(?!_)(?=punct)|(?!_)punct(_+)(?!_)(?=punct)|(?:(?!_)punct|notPunctSpace)(_+)(?!_)(?=notPunctSpace)",r6=Ie(t6,"gu").replace(/notPunctSpace/g,rf).replace(/punctSpace/g,ll).replace(/punct/g,go).getRegex(),n6=Ie(/^~~?(?:((?!~)punct)|[^\s~])/,"u").replace(/punct/g,go).getRegex(),i6="^[^~]+(?=[^~])|(?!~)punct(~~?)(?=[\\s]|$)|notPunctSpace(~~?)(?!~)(?=punctSpace|$)|(?!~)punctSpace(~~?)(?=notPunctSpace)|[\\s](~~?)(?!~)(?=punct)|(?!~)punct(~~?)(?!~)(?=punct)|notPunctSpace(~~?)(?=notPunctSpace)",o6=Ie(i6,"gu").replace(/notPunctSpace/g,rf).replace(/punctSpace/g,ll).replace(/punct/g,go).getRegex(),a6=Ie(/\\(punct)/,"gu").replace(/punct/g,go).getRegex(),s6=Ie(/^<(scheme:[^\s\x00-\x1f<>]*|email)>/).replace("scheme",/[a-zA-Z][a-zA-Z0-9+.-]{1,31}/).replace("email",/[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+(@)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)+(?![-_])/).getRegex(),c6=Ie(CR).replace("(?:-->|$)","-->").getRegex(),l6=Ie("^comment|^</[a-zA-Z][\\w:-]*\\s*>|^<[a-zA-Z][\\w-]*(?:attribute)*?\\s*/?>|^<\\?[\\s\\S]*?\\?>|^<![a-zA-Z]+\\s[\\s\\S]*?>|^<!\\[CDATA\\[[\\s\\S]*?\\]\\]>").replace("comment",c6).replace("attribute",/\s+[a-zA-Z:_][\w.:-]*(?:\s*=\s*"[^"]*"|\s*=\s*'[^']*'|\s*=\s*[^\s"'=<>`]+)?/).getRegex(),rg=/(?:\[(?:\\[\s\S]|[^\[\]\\])*\]|\\[\s\S]|`+(?!`)[^`]*?`+(?!`)|``+(?=\])|[^\[\]\\`])*?/,u6=Ie(/^!?\[(label)\]\(\s*(href)(?:(?:[ \t]+(?:\n[ \t]*)?|\n[ \t]*)(title))?\s*\)/).replace("label",rg).replace("href",/<(?:\\.|[^\n<>\\])+>|[^ \t\n\x00-\x1f]+|(?=\))/).replace("title",/"(?:\\"?|[^"\\])*"|'(?:\\'?|[^'\\])*'|\((?:\\\)?|[^)\\])*\)/).getRegex(),g0=Ie(/^!?\[(label)\]\[(ref)\]/).replace("label",rg).replace("ref",ER).getRegex(),v0=Ie(/^!?\[(ref)\](?:\[\])?/).replace("ref",ER).getRegex(),d6=Ie("reflink|nolink(?!\\()","g").replace("reflink",g0).replace("nolink",v0).getRegex(),r0=/[hH][tT][tT][pP][sS]?|[fF][tT][pP]/,IR={_backpedal:As,anyPunctuation:a6,autolink:s6,blockSkip:Q9,br:f0,code:q9,del:As,delLDelim:As,delRDelim:As,emStrongLDelim:U9,emStrongRDelimAst:G9,emStrongRDelimUnd:e6,escape:W9,link:u6,nolink:v0,punctuation:V9,reflink:g0,reflinkSearch:d6,tag:l6,text:L9,url:As},f6={...IR,emStrongLDelim:K9,emStrongRDelimAst:Z9,emStrongRDelimUnd:r6,link:Ie(/^!?\[(label)\]\((.*?)\)/).replace("label",rg).getRegex(),reflink:Ie(/^!?\[(label)\]\s*\[([^\]]*)\]/).replace("label",rg).getRegex()},kR={...IR,emStrongRDelimAst:Y9,emStrongLDelim:J9,delLDelim:n6,delRDelim:o6,url:Ie(/^((?:protocol):\/\/|www\.)(?:[a-zA-Z0-9\-]+\.?)+[^\s<]*|^email/).replace("protocol",r0).replace("email",/[A-Za-z0-9._+-]+(@)[a-zA-Z0-9-_]+(?:\.[a-zA-Z0-9-_]*[a-zA-Z0-9])+(?![-_])/).getRegex(),_backpedal:/(?:[^?!.,:;*_'"~()&]+|\([^)]*\)|&(?![a-zA-Z0-9]+;$)|[?!.,:;*_'"~)]+(?!$))+/,del:/^(~~?)(?=[^\s~])((?:\\[\s\S]|[^\\])*?(?:\\[\s\S]|[^\s~\\]))\1(?=[^~]|$)/,text:Ie(/^(`+|~+|[^`~])(?:(?=[`~])|(?= {2,}\n)|(?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)|[\s\S]*?(?:(?=[\\<!\[`*~_]|\b_|protocol:\/\/|www\.|$)|[^ ](?= {2,}\n)|[^a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-](?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)))/).replace("protocol",r0).getRegex()},p6={...kR,br:Ie(f0).replace("{2,}","*").getRegex(),text:Ie(kR.text).replace("\\b_","\\b_| {2,}\\n").replace(/\{2,\}/g,"*").getRegex()},tg={normal:_R,gfm:D9,pedantic:B9},Zd={normal:IR,gfm:kR,breaks:p6,pedantic:f6},m6={"&":"&","<":"<",">":">",'"':""","'":"'"},n0=e=>m6[e];ng=class{options;rules;lexer;constructor(e){this.options=e||Ns}space(e){let t=this.rules.block.newline.exec(e);if(t&&t[0].length>0)return{type:"space",raw:t[0]}}code(e){let t=this.rules.block.code.exec(e);if(t){let r=this.options.pedantic?t[0]:a0(t[0]),n=r.replace(this.rules.other.codeRemoveIndent,"");return{type:"code",raw:r,codeBlockStyle:"indented",text:n}}}fences(e){let t=this.rules.block.fences.exec(e);if(t){let r=t[0],n=v6(r,t[3]||"",this.rules);return{type:"code",raw:r,lang:t[2]?t[2].trim().replace(this.rules.inline.anyPunctuation,"$1"):t[2],text:n}}}heading(e){let t=this.rules.block.heading.exec(e);if(t){let r=t[2].trim();if(this.rules.other.endingHash.test(r)){let n=ha(r,"#");(this.options.pedantic||!n||this.rules.other.endingSpaceChar.test(n))&&(r=n.trim())}return{type:"heading",raw:ha(t[0],`
|
|
236
|
+
`),depth:t[1].length,text:r,tokens:this.lexer.inline(r)}}}hr(e){let t=this.rules.block.hr.exec(e);if(t)return{type:"hr",raw:ha(t[0],`
|
|
237
|
+
`)}}blockquote(e){let t=this.rules.block.blockquote.exec(e);if(t){let r=ha(t[0],`
|
|
238
|
+
`).split(`
|
|
239
|
+
`),n="",i="",o=[];for(;r.length>0;){let a=!1,s=[],c;for(c=0;c<r.length;c++)if(this.rules.other.blockquoteStart.test(r[c]))s.push(r[c]),a=!0;else if(!a)s.push(r[c]);else break;r=r.slice(c);let l=s.join(`
|
|
240
|
+
`),u=l.replace(this.rules.other.blockquoteSetextReplace,`
|
|
241
|
+
$1`).replace(this.rules.other.blockquoteSetextReplace2,"");n=n?`${n}
|
|
242
|
+
${l}`:l,i=i?`${i}
|
|
243
|
+
${u}`:u;let f=this.lexer.state.top;if(this.lexer.state.top=!0,this.lexer.blockTokens(u,o,!0),this.lexer.state.top=f,r.length===0)break;let d=o.at(-1);if(d?.type==="code")break;if(d?.type==="blockquote"){let p=d,m=r.join(`
|
|
244
|
+
`),h=p.raw+`
|
|
245
|
+
`+m.replace(this.rules.other.blockquoteSetextReplace2,""),g=this.blockquote(h);o[o.length-1]=g,n=`${n}
|
|
246
|
+
${m}`,i=i.substring(0,i.length-p.text.length)+g.text;break}else if(d?.type==="list"){let p=d,m=p.raw+`
|
|
247
|
+
`+r.join(`
|
|
248
|
+
`),h=this.list(m);o[o.length-1]=h,n=n.substring(0,n.length-d.raw.length)+h.raw,i=i.substring(0,i.length-p.raw.length)+h.raw,r=m.substring(o.at(-1).raw.length).split(`
|
|
249
|
+
`);continue}}return{type:"blockquote",raw:n,tokens:o,text:i}}}list(e){let t=this.rules.block.list.exec(e);if(t){let r=t[1].trim(),n=r.length>1,i={type:"list",raw:"",ordered:n,start:n?+r.slice(0,-1):"",loose:!1,items:[]};r=n?`\\d{1,9}\\${r.slice(-1)}`:`\\${r}`,this.options.pedantic&&(r=n?r:"[*+-]");let o=this.rules.other.listItemRegex(r),a=!1;for(;e;){let c=!1,l="",u="";if(!(t=o.exec(e))||this.rules.block.hr.test(e))break;l=t[0],e=e.substring(l.length);let f=g6(t[2].split(`
|
|
250
|
+
`,1)[0],t[1].length),d=e.split(`
|
|
251
|
+
`,1)[0],p=!f.trim(),m=0;if(this.options.pedantic?(m=2,u=f.trimStart()):p?m=t[1].length+1:(m=f.search(this.rules.other.nonSpaceChar),m=m>4?1:m,u=f.slice(m),m+=t[1].length),p&&this.rules.other.blankLine.test(d)&&(l+=d+`
|
|
252
|
+
`,e=e.substring(d.length+1),c=!0),!c){let h=this.rules.other.nextBulletRegex(m),g=this.rules.other.hrRegex(m),v=this.rules.other.fencesBeginRegex(m),w=this.rules.other.headingBeginRegex(m),y=this.rules.other.htmlBeginRegex(m),R=this.rules.other.blockquoteBeginRegex(m);for(;e;){let N=e.split(`
|
|
253
|
+
`,1)[0],b;if(d=N,this.options.pedantic?(d=d.replace(this.rules.other.listReplaceNesting," "),b=d):b=d.replace(this.rules.other.tabCharGlobal," "),v.test(d)||w.test(d)||y.test(d)||R.test(d)||h.test(d)||g.test(d))break;if(b.search(this.rules.other.nonSpaceChar)>=m||!d.trim())u+=`
|
|
254
|
+
`+b.slice(m);else{if(p||f.replace(this.rules.other.tabCharGlobal," ").search(this.rules.other.nonSpaceChar)>=4||v.test(f)||w.test(f)||g.test(f))break;u+=`
|
|
255
|
+
`+d}p=!d.trim(),l+=N+`
|
|
256
|
+
`,e=e.substring(N.length+1),f=b.slice(m)}}i.loose||(a?i.loose=!0:this.rules.other.doubleBlankLine.test(l)&&(a=!0)),i.items.push({type:"list_item",raw:l,task:!!this.options.gfm&&this.rules.other.listIsTask.test(u),loose:!1,text:u,tokens:[]}),i.raw+=l}let s=i.items.at(-1);if(s)s.raw=s.raw.trimEnd(),s.text=s.text.trimEnd();else return;i.raw=i.raw.trimEnd();for(let c of i.items)if(this.lexer.state.top=!1,c.tokens=this.lexer.blockTokens(c.text,[]),!i.loose){let l=c.tokens.filter(f=>f.type==="space"),u=l.length>0&&l.some(f=>this.rules.other.anyLine.test(f.raw));i.loose=u}for(let c of i.items){let l=c.tokens[0];if(c.task&&(l?.type==="text"||l?.type==="paragraph")){c.text=c.text.replace(this.rules.other.listReplaceTask,""),l.raw=l.raw.replace(this.rules.other.listReplaceTask,""),l.text=l.text.replace(this.rules.other.listReplaceTask,"");for(let f=this.lexer.inlineQueue.length-1;f>=0;f--)if(this.rules.other.listIsTask.test(this.lexer.inlineQueue[f].src)){this.lexer.inlineQueue[f].src=this.lexer.inlineQueue[f].src.replace(this.rules.other.listReplaceTask,"");break}let u=this.rules.other.listTaskCheckbox.exec(c.raw);if(u){let f={type:"checkbox",raw:u[0]+" ",checked:u[0]!=="[ ]"};c.checked=f.checked,i.loose?c.tokens[0]&&["paragraph","text"].includes(c.tokens[0].type)&&"tokens"in c.tokens[0]&&c.tokens[0].tokens?(c.tokens[0].raw=f.raw+c.tokens[0].raw,c.tokens[0].text=f.raw+c.tokens[0].text,c.tokens[0].tokens.unshift(f)):c.tokens.unshift({type:"paragraph",raw:f.raw,text:f.raw,tokens:[f]}):c.tokens.unshift(f)}}else c.task&&(c.task=!1)}if(i.loose)for(let c of i.items){c.loose=!0;for(let l of c.tokens)l.type==="text"&&(l.type="paragraph")}return i}}html(e){let t=this.rules.block.html.exec(e);if(t){let r=a0(t[0]);return{type:"html",block:!0,raw:r,pre:t[1]==="pre"||t[1]==="script"||t[1]==="style",text:r}}}def(e){let t=this.rules.block.def.exec(e);if(t){let r=t[1].toLowerCase().replace(this.rules.other.multipleSpaceGlobal," "),n=t[2]?t[2].replace(this.rules.other.hrefBrackets,"$1").replace(this.rules.inline.anyPunctuation,"$1"):"",i=t[3]?t[3].substring(1,t[3].length-1).replace(this.rules.inline.anyPunctuation,"$1"):t[3];return{type:"def",tag:r,raw:ha(t[0],`
|
|
257
|
+
`),href:n,title:i}}}table(e){let t=this.rules.block.table.exec(e);if(!t||!this.rules.other.tableDelimiter.test(t[2]))return;let r=o0(t[1]),n=t[2].replace(this.rules.other.tableAlignChars,"").split("|"),i=t[3]?.trim()?t[3].replace(this.rules.other.tableRowBlankLine,"").split(`
|
|
258
|
+
`):[],o={type:"table",raw:ha(t[0],`
|
|
259
|
+
`),header:[],align:[],rows:[]};if(r.length===n.length){for(let a of n)this.rules.other.tableAlignRight.test(a)?o.align.push("right"):this.rules.other.tableAlignCenter.test(a)?o.align.push("center"):this.rules.other.tableAlignLeft.test(a)?o.align.push("left"):o.align.push(null);for(let a=0;a<r.length;a++)o.header.push({text:r[a],tokens:this.lexer.inline(r[a]),header:!0,align:o.align[a]});for(let a of i)o.rows.push(o0(a,o.header.length).map((s,c)=>({text:s,tokens:this.lexer.inline(s),header:!1,align:o.align[c]})));return o}}lheading(e){let t=this.rules.block.lheading.exec(e);if(t){let r=t[1].trim();return{type:"heading",raw:ha(t[0],`
|
|
260
|
+
`),depth:t[2].charAt(0)==="="?1:2,text:r,tokens:this.lexer.inline(r)}}}paragraph(e){let t=this.rules.block.paragraph.exec(e);if(t){let r=t[1].charAt(t[1].length-1)===`
|
|
261
|
+
`?t[1].slice(0,-1):t[1];return{type:"paragraph",raw:t[0],text:r,tokens:this.lexer.inline(r)}}}text(e){let t=this.rules.block.text.exec(e);if(t)return{type:"text",raw:t[0],text:t[0],tokens:this.lexer.inline(t[0])}}escape(e){let t=this.rules.inline.escape.exec(e);if(t)return{type:"escape",raw:t[0],text:t[1]}}tag(e){let t=this.rules.inline.tag.exec(e);if(t)return!this.lexer.state.inLink&&this.rules.other.startATag.test(t[0])?this.lexer.state.inLink=!0:this.lexer.state.inLink&&this.rules.other.endATag.test(t[0])&&(this.lexer.state.inLink=!1),!this.lexer.state.inRawBlock&&this.rules.other.startPreScriptTag.test(t[0])?this.lexer.state.inRawBlock=!0:this.lexer.state.inRawBlock&&this.rules.other.endPreScriptTag.test(t[0])&&(this.lexer.state.inRawBlock=!1),{type:"html",raw:t[0],inLink:this.lexer.state.inLink,inRawBlock:this.lexer.state.inRawBlock,block:!1,text:t[0]}}link(e){let t=this.rules.inline.link.exec(e);if(t){let r=t[2].trim();if(!this.options.pedantic&&this.rules.other.startAngleBracket.test(r)){if(!this.rules.other.endAngleBracket.test(r))return;let o=ha(r.slice(0,-1),"\\");if((r.length-o.length)%2===0)return}else{let o=h6(t[2],"()");if(o===-2)return;if(o>-1){let a=(t[0].indexOf("!")===0?5:4)+t[1].length+o;t[2]=t[2].substring(0,o),t[0]=t[0].substring(0,a).trim(),t[3]=""}}let n=t[2],i="";if(this.options.pedantic){let o=this.rules.other.pedanticHrefTitle.exec(n);o&&(n=o[1],i=o[3])}else i=t[3]?t[3].slice(1,-1):"";return n=n.trim(),this.rules.other.startAngleBracket.test(n)&&(this.options.pedantic&&!this.rules.other.endAngleBracket.test(r)?n=n.slice(1):n=n.slice(1,-1)),s0(t,{href:n&&n.replace(this.rules.inline.anyPunctuation,"$1"),title:i&&i.replace(this.rules.inline.anyPunctuation,"$1")},t[0],this.lexer,this.rules)}}reflink(e,t){let r;if((r=this.rules.inline.reflink.exec(e))||(r=this.rules.inline.nolink.exec(e))){let n=(r[2]||r[1]).replace(this.rules.other.multipleSpaceGlobal," "),i=t[n.toLowerCase()];if(!i){let o=r[0].charAt(0);return{type:"text",raw:o,text:o}}return s0(r,i,r[0],this.lexer,this.rules)}}emStrong(e,t,r=""){let n=this.rules.inline.emStrongLDelim.exec(e);if(!(!n||!n[1]&&!n[2]&&!n[3]&&!n[4]||n[4]&&r.match(this.rules.other.unicodeAlphaNumeric))&&(!(n[1]||n[3])||!r||this.rules.inline.punctuation.exec(r))){let i=[...n[0]].length-1,o,a,s=i,c=0,l=n[0][0],u=r===l,f=l==="*"?this.rules.inline.emStrongRDelimAst:this.rules.inline.emStrongRDelimUnd;for(f.lastIndex=0,t=t.slice(-1*e.length+i);(n=f.exec(t))!==null;){if(o=n[1]||n[2]||n[3]||n[4]||n[5]||n[6],!o)continue;if(a=[...o].length,n[3]||n[4]){s+=a;continue}else if(n[5]||n[6]){if(i%3&&!((i+a)%3)){c+=a;continue}if(u)break}if(s-=a,s>0)continue;a=Math.min(a,a+s+c);let d=[...n[0]][0].length,p=e.slice(0,i+n.index+d+a);if(Math.min(i,a)%2){let h=p.slice(1,-1);return{type:"em",raw:p,text:h,tokens:this.lexer.inlineTokens(h)}}let m=p.slice(2,-2);return{type:"strong",raw:p,text:m,tokens:this.lexer.inlineTokens(m)}}}}codespan(e){let t=this.rules.inline.code.exec(e);if(t){let r=t[2].replace(this.rules.other.newLineCharGlobal," "),n=this.rules.other.nonSpaceChar.test(r),i=this.rules.other.startingSpaceChar.test(r)&&this.rules.other.endingSpaceChar.test(r);return n&&i&&(r=r.substring(1,r.length-1)),{type:"codespan",raw:t[0],text:r}}}br(e){let t=this.rules.inline.br.exec(e);if(t)return{type:"br",raw:t[0]}}del(e,t,r=""){let n=this.rules.inline.delLDelim.exec(e);if(n&&(!n[1]||!r||this.rules.inline.punctuation.exec(r))){let i=[...n[0]].length-1,o,a,s=i,c=this.rules.inline.delRDelim;for(c.lastIndex=0,t=t.slice(-1*e.length+i);(n=c.exec(t))!==null;){if(o=n[1]||n[2]||n[3]||n[4]||n[5]||n[6],!o||(a=[...o].length,a!==i))continue;if(n[3]||n[4]){s+=a;continue}if(s-=a,s>0)continue;a=Math.min(a,a+s);let l=[...n[0]][0].length,u=e.slice(0,i+n.index+l+a),f=u.slice(i,-i);return{type:"del",raw:u,text:f,tokens:this.lexer.inlineTokens(f)}}}}autolink(e){let t=this.rules.inline.autolink.exec(e);if(t){let r,n;return t[2]==="@"?(r=t[1],n="mailto:"+r):(r=t[1],n=r),{type:"link",raw:t[0],text:r,href:n,tokens:[{type:"text",raw:r,text:r}]}}}url(e){let t;if(t=this.rules.inline.url.exec(e)){let r,n;if(t[2]==="@")r=t[0],n="mailto:"+r;else{let i;do i=t[0],t[0]=this.rules.inline._backpedal.exec(t[0])?.[0]??"";while(i!==t[0]);r=t[0],t[1]==="www."?n="http://"+t[0]:n=t[0]}return{type:"link",raw:t[0],text:r,href:n,tokens:[{type:"text",raw:r,text:r}]}}}inlineText(e){let t=this.rules.inline.text.exec(e);if(t){let r=this.lexer.state.inRawBlock;return{type:"text",raw:t[0],text:t[0],escaped:r}}}},Wr=class bR{tokens;options;state;inlineQueue;tokenizer;constructor(t){this.tokens=[],this.tokens.links=Object.create(null),this.options=t||Ns,this.options.tokenizer=this.options.tokenizer||new ng,this.tokenizer=this.options.tokenizer,this.tokenizer.options=this.options,this.tokenizer.lexer=this,this.inlineQueue=[],this.state={inLink:!1,inRawBlock:!1,linkEmitted:!1,top:!0};let r={other:yr,block:tg.normal,inline:Zd.normal};this.options.pedantic?(r.block=tg.pedantic,r.inline=Zd.pedantic):this.options.gfm&&(r.block=tg.gfm,this.options.breaks?r.inline=Zd.breaks:r.inline=Zd.gfm),this.tokenizer.rules=r}static get rules(){return{block:tg,inline:Zd}}static lex(t,r){return new bR(r).lex(t)}static lexInline(t,r){return new bR(r).inlineTokens(t)}lex(t){t=t.replace(yr.carriageReturn,`
|
|
262
|
+
`),this.blockTokens(t,this.tokens);for(let r=0;r<this.inlineQueue.length;r++){let n=this.inlineQueue[r];this.inlineTokens(n.src,n.tokens)}return this.inlineQueue=[],this.tokens}blockTokens(t,r=[],n=!1){this.tokenizer.lexer=this,this.options.pedantic&&(t=t.replace(yr.tabCharGlobal," ").replace(yr.spaceLine,""));let i=1/0;for(;t;){if(t.length<i)i=t.length;else{this.infiniteLoopError(t.charCodeAt(0));break}let o;if(this.options.extensions?.block?.some(s=>(o=s.call({lexer:this},t,r))?(t=t.substring(o.raw.length),r.push(o),!0):!1))continue;if(o=this.tokenizer.space(t)){t=t.substring(o.raw.length);let s=r.at(-1);o.raw.length===1&&s!==void 0?s.raw+=`
|
|
263
|
+
`:r.push(o);continue}if(o=this.tokenizer.code(t)){t=t.substring(o.raw.length);let s=r.at(-1);s?.type==="paragraph"||s?.type==="text"?(s.raw+=(s.raw.endsWith(`
|
|
264
|
+
`)?"":`
|
|
265
|
+
`)+o.raw,s.text+=`
|
|
266
|
+
`+o.text,this.inlineQueue.at(-1).src=s.text):r.push(o);continue}if(o=this.tokenizer.fences(t)){t=t.substring(o.raw.length),r.push(o);continue}if(o=this.tokenizer.heading(t)){t=t.substring(o.raw.length),r.push(o);continue}if(o=this.tokenizer.hr(t)){t=t.substring(o.raw.length),r.push(o);continue}if(o=this.tokenizer.blockquote(t)){t=t.substring(o.raw.length),r.push(o);continue}if(o=this.tokenizer.list(t)){t=t.substring(o.raw.length),r.push(o);continue}if(o=this.tokenizer.html(t)){t=t.substring(o.raw.length),r.push(o);continue}if(o=this.tokenizer.def(t)){t=t.substring(o.raw.length);let s=r.at(-1);s?.type==="paragraph"||s?.type==="text"?(s.raw+=(s.raw.endsWith(`
|
|
267
|
+
`)?"":`
|
|
268
|
+
`)+o.raw,s.text+=`
|
|
269
|
+
`+o.raw,this.inlineQueue.at(-1).src=s.text):this.tokens.links[o.tag]||(this.tokens.links[o.tag]={href:o.href,title:o.title},r.push(o));continue}if(o=this.tokenizer.table(t)){t=t.substring(o.raw.length),r.push(o);continue}if(o=this.tokenizer.lheading(t)){t=t.substring(o.raw.length),r.push(o);continue}let a=t;if(this.options.extensions?.startBlock){let s=1/0,c=t.slice(1),l;this.options.extensions.startBlock.forEach(u=>{l=u.call({lexer:this},c),typeof l=="number"&&l>=0&&(s=Math.min(s,l))}),s<1/0&&s>=0&&(a=t.substring(0,s+1))}if(this.state.top&&(o=this.tokenizer.paragraph(a))){let s=r.at(-1);n&&s?.type==="paragraph"?(s.raw+=(s.raw.endsWith(`
|
|
270
|
+
`)?"":`
|
|
271
|
+
`)+o.raw,s.text+=`
|
|
272
|
+
`+o.text,this.inlineQueue.pop(),this.inlineQueue.at(-1).src=s.text):r.push(o),n=a.length!==t.length,t=t.substring(o.raw.length);continue}if(o=this.tokenizer.text(t)){t=t.substring(o.raw.length);let s=r.at(-1);s?.type==="text"?(s.raw+=(s.raw.endsWith(`
|
|
273
|
+
`)?"":`
|
|
274
|
+
`)+o.raw,s.text+=`
|
|
275
|
+
`+o.text,this.inlineQueue.pop(),this.inlineQueue.at(-1).src=s.text):r.push(o);continue}if(t){this.infiniteLoopError(t.charCodeAt(0));break}}return this.state.top=!0,r}inline(t,r=[]){return this.inlineQueue.push({src:t,tokens:r}),r}linkInText(t){if(!t.includes("["))return!1;let r=this.tokenizer.rules.inline.link;for(let n of t.matchAll(this.tokenizer.rules.inline.blockSkip))if(r.test(n[0])&&t.charAt(n.index-1)!=="!")return!0;for(let n of t.matchAll(this.tokenizer.rules.inline.reflinkSearch)){let i=n[0],o=i.lastIndexOf("[");if(!(i.charAt(0)==="!"||!Object.hasOwn(this.tokens.links,i.slice(o+1,-1)))&&!(o>1&&this.linkInText(i.slice(1,o-1))))return!0}return!1}inlineTokens(t,r=[]){this.tokenizer.lexer=this;let n=t;if(this.tokens.links&&t.includes("[")){let s=this.tokenizer.rules.inline.reflinkSearch,c=l=>{let u=l.lastIndexOf("[");if(!Object.hasOwn(this.tokens.links,l.slice(u+1,-1)))return l;if(u>1&&l.charAt(0)!=="!"){let f=l.slice(1,u-1);if(this.linkInText(f))return"["+f.replace(s,c)+"]["+"a".repeat(l.length-u-2)+"]"}return"["+"a".repeat(l.length-2)+"]"};n=n.replace(s,c)}n=n.replace(this.tokenizer.rules.inline.anyPunctuation,s=>"+".repeat(s.length)),n=n.replace(this.tokenizer.rules.inline.blockSkip,(s,c,l)=>{let u=l?l.length:0;return s.slice(0,u)+"["+"a".repeat(s.length-u-2)+"]"}),n=this.options.hooks?.emStrongMask?.call({lexer:this},n)??n;let i=!1,o="",a=1/0;for(;t;){if(t.length<a)a=t.length;else{this.infiniteLoopError(t.charCodeAt(0));break}i||(o=""),i=!1;let s;if(this.options.extensions?.inline?.some(l=>(s=l.call({lexer:this},t,r))?(t=t.substring(s.raw.length),r.push(s),!0):!1))continue;if(s=this.tokenizer.escape(t)){t=t.substring(s.raw.length),r.push(s);continue}if(s=this.tokenizer.tag(t)){t=t.substring(s.raw.length),r.push(s);continue}if(s=this.tokenizer.link(t)){t=t.substring(s.raw.length),r.push(s);continue}if(s=this.tokenizer.reflink(t,this.tokens.links)){t=t.substring(s.raw.length);let l=r.at(-1);s.type==="text"&&l?.type==="text"?(l.raw+=s.raw,l.text+=s.text):r.push(s);continue}if(s=this.tokenizer.emStrong(t,n,o)){t=t.substring(s.raw.length),r.push(s);continue}if(s=this.tokenizer.codespan(t)){t=t.substring(s.raw.length),r.push(s);continue}if(s=this.tokenizer.br(t)){t=t.substring(s.raw.length),r.push(s);continue}if(s=this.tokenizer.del(t,n,o)){t=t.substring(s.raw.length),r.push(s);continue}if(s=this.tokenizer.autolink(t)){t=t.substring(s.raw.length),r.push(s);continue}if(!this.state.inLink&&(s=this.tokenizer.url(t))){t=t.substring(s.raw.length),r.push(s);continue}let c=t;if(this.options.extensions?.startInline){let l=1/0,u=t.slice(1),f;this.options.extensions.startInline.forEach(d=>{f=d.call({lexer:this},u),typeof f=="number"&&f>=0&&(l=Math.min(l,f))}),l<1/0&&l>=0&&(c=t.substring(0,l+1))}if(s=this.tokenizer.inlineText(c)){t=t.substring(s.raw.length),s.raw.slice(-1)!=="_"&&(o=s.raw.slice(-1)),i=!0;let l=r.at(-1);l?.type==="text"?(l.raw+=s.raw,l.text+=s.text):r.push(s);continue}if(t){this.infiniteLoopError(t.charCodeAt(0));break}}return r}infiniteLoopError(t){let r="Infinite loop on byte: "+t;if(this.options.silent)console.error(r);else throw new Error(r)}},ig=class{options;parser;constructor(e){this.options=e||Ns}space(e){return""}code({text:e,lang:t,escaped:r}){let n=(t||"").match(yr.notSpaceStart)?.[0],i=e.replace(yr.endingNewline,"")+`
|
|
276
|
+
`;return n?'<pre><code class="language-'+Wi(n)+'">'+(r?i:Wi(i,!0))+`</code></pre>
|
|
277
|
+
`:"<pre><code>"+(r?i:Wi(i,!0))+`</code></pre>
|
|
278
|
+
`}blockquote({tokens:e}){return`<blockquote>
|
|
279
|
+
${this.parser.parse(e)}</blockquote>
|
|
280
|
+
`}html({text:e}){return e}def(e){return""}heading({tokens:e,depth:t}){return`<h${t}>${this.parser.parseInline(e)}</h${t}>
|
|
281
|
+
`}hr(e){return`<hr>
|
|
282
|
+
`}list(e){let t=e.ordered,r=e.start,n="";for(let a=0;a<e.items.length;a++){let s=e.items[a];n+=this.listitem(s)}let i=t?"ol":"ul",o=t&&r!==1?' start="'+r+'"':"";return"<"+i+o+`>
|
|
283
|
+
`+n+"</"+i+`>
|
|
284
|
+
`}listitem(e){return`<li>${this.parser.parse(e.tokens)}</li>
|
|
285
|
+
`}checkbox({checked:e}){return"<input "+(e?'checked="" ':"")+'disabled="" type="checkbox"> '}paragraph({tokens:e}){return`<p>${this.parser.parseInline(e)}</p>
|
|
286
|
+
`}table(e){let t="",r="";for(let i=0;i<e.header.length;i++)r+=this.tablecell(e.header[i]);t+=this.tablerow({text:r});let n="";for(let i=0;i<e.rows.length;i++){let o=e.rows[i];r="";for(let a=0;a<o.length;a++)r+=this.tablecell(o[a]);n+=this.tablerow({text:r})}return n&&(n=`<tbody>${n}</tbody>`),`<table>
|
|
287
|
+
<thead>
|
|
288
|
+
`+t+`</thead>
|
|
289
|
+
`+n+`</table>
|
|
290
|
+
`}tablerow({text:e}){return`<tr>
|
|
291
|
+
${e}</tr>
|
|
292
|
+
`}tablecell(e){let t=this.parser.parseInline(e.tokens),r=e.header?"th":"td";return(e.align?`<${r} align="${e.align}">`:`<${r}>`)+t+`</${r}>
|
|
293
|
+
`}strong({tokens:e}){return`<strong>${this.parser.parseInline(e)}</strong>`}em({tokens:e}){return`<em>${this.parser.parseInline(e)}</em>`}codespan({text:e}){return`<code>${Wi(e,!0)}</code>`}br(e){return"<br>"}del({tokens:e}){return`<del>${this.parser.parseInline(e)}</del>`}link({href:e,title:t,tokens:r}){let n=this.parser.parseInline(r),i=i0(e);if(i===null)return n;e=i;let o='<a href="'+e+'"';return t&&(o+=' title="'+Wi(t)+'"'),o+=">"+n+"</a>",o}image({href:e,title:t,text:r,tokens:n}){n&&(r=this.parser.parseInline(n,this.parser.textRenderer));let i=i0(e);if(i===null)return Wi(r);e=i;let o=`<img src="${e}" alt="${Wi(r)}"`;return t&&(o+=` title="${Wi(t)}"`),o+=">",o}text(e){return"tokens"in e&&e.tokens?this.parser.parseInline(e.tokens):"escaped"in e&&e.escaped?e.text:Wi(e.text)}},xR=class{strong({text:e}){return e}em({text:e}){return e}codespan({text:e}){return e}del({text:e}){return e}html({text:e}){return e}text({text:e}){return e}link({text:e}){return""+e}image({text:e}){return""+e}br(){return""}checkbox({raw:e}){return e}},ui=class AR{options;renderer;textRenderer;constructor(t){this.options=t||Ns,this.options.renderer=this.options.renderer||new ig,this.renderer=this.options.renderer,this.renderer.options=this.options,this.renderer.parser=this,this.textRenderer=new xR}static parse(t,r){return new AR(r).parse(t)}static parseInline(t,r){return new AR(r).parseInline(t)}parse(t){this.renderer.parser=this;let r="";for(let n=0;n<t.length;n++){let i=t[n];if(this.options.extensions?.renderers?.[i.type]){let a=i,s=this.options.extensions.renderers[a.type].call({parser:this},a);if(s!==!1||!["space","hr","heading","code","table","blockquote","list","checkbox","html","def","paragraph","text"].includes(a.type)){r+=s||"";continue}}let o=i;switch(o.type){case"space":{r+=this.renderer.space(o);break}case"hr":{r+=this.renderer.hr(o);break}case"heading":{r+=this.renderer.heading(o);break}case"code":{r+=this.renderer.code(o);break}case"table":{r+=this.renderer.table(o);break}case"blockquote":{r+=this.renderer.blockquote(o);break}case"list":{r+=this.renderer.list(o);break}case"checkbox":{r+=this.renderer.checkbox(o);break}case"html":{r+=this.renderer.html(o);break}case"def":{r+=this.renderer.def(o);break}case"paragraph":{r+=this.renderer.paragraph(o);break}case"text":{r+=this.renderer.text(o);break}default:{let a='Token with "'+o.type+'" type was not found.';if(this.options.silent)return console.error(a),"";throw new Error(a)}}}return r}parseInline(t,r=this.renderer){this.renderer.parser=this;let n="";for(let i=0;i<t.length;i++){let o=t[i];if(this.options.extensions?.renderers?.[o.type]){let s=this.options.extensions.renderers[o.type].call({parser:this},o);if(s!==!1||!["escape","html","link","image","checkbox","strong","em","codespan","br","del","text"].includes(o.type)){n+=s||"";continue}}let a=o;switch(a.type){case"escape":{n+=r.text(a);break}case"html":{n+=r.html(a);break}case"link":{n+=r.link(a);break}case"image":{n+=r.image(a);break}case"checkbox":{n+=r.checkbox(a);break}case"strong":{n+=r.strong(a);break}case"em":{n+=r.em(a);break}case"codespan":{n+=r.codespan(a);break}case"br":{n+=r.br(a);break}case"del":{n+=r.del(a);break}case"text":{n+=r.text(a);break}default:{let s='Token with "'+a.type+'" type was not found.';if(this.options.silent)return console.error(s),"";throw new Error(s)}}}return n}},ef=class{options;block;constructor(e){this.options=e||Ns}static passThroughHooks=new Set(["preprocess","postprocess","processAllTokens","emStrongMask"]);static passThroughHooksRespectAsync=new Set(["preprocess","postprocess","processAllTokens"]);preprocess(e){return e}postprocess(e){return e}processAllTokens(e){return e}emStrongMask(e){return e}provideLexer(e=this.block){return e?Wr.lex:Wr.lexInline}provideParser(e=this.block){return e?ui.parse:ui.parseInline}},w6=class{defaults=RR();options=this.setOptions;parse=this.parseMarkdown(!0);parseInline=this.parseMarkdown(!1);Parser=ui;Renderer=ig;TextRenderer=xR;Lexer=Wr;Tokenizer=ng;Hooks=ef;constructor(...e){this.use(...e)}walkTokens(e,t){let r=[];for(let n of e)switch(r=r.concat(t.call(this,n)),n.type){case"table":{let i=n;for(let o of i.header)r=r.concat(this.walkTokens(o.tokens,t));for(let o of i.rows)for(let a of o)r=r.concat(this.walkTokens(a.tokens,t));break}case"list":{let i=n;r=r.concat(this.walkTokens(i.items,t));break}default:{let i=n;this.defaults.extensions?.childTokens?.[i.type]?this.defaults.extensions.childTokens[i.type].forEach(o=>{let a=i[o].flat(1/0);r=r.concat(this.walkTokens(a,t))}):i.tokens&&(r=r.concat(this.walkTokens(i.tokens,t)))}}return r}use(...e){let t=this.defaults.extensions||{renderers:{},childTokens:{}};return e.forEach(r=>{let n={...r};if(n.async=this.defaults.async||n.async||!1,r.extensions&&(r.extensions.forEach(i=>{if(!i.name)throw new Error("extension name required");if("renderer"in i){let o=t.renderers[i.name];o?t.renderers[i.name]=function(...a){let s=i.renderer.apply(this,a);return s===!1&&(s=o.apply(this,a)),s}:t.renderers[i.name]=i.renderer}if("tokenizer"in i){if(!i.level||i.level!=="block"&&i.level!=="inline")throw new Error("extension level must be 'block' or 'inline'");let o=t[i.level];o?o.unshift(i.tokenizer):t[i.level]=[i.tokenizer],i.start&&(i.level==="block"?t.startBlock?t.startBlock.push(i.start):t.startBlock=[i.start]:i.level==="inline"&&(t.startInline?t.startInline.push(i.start):t.startInline=[i.start]))}"childTokens"in i&&i.childTokens&&(t.childTokens[i.name]=i.childTokens)}),n.extensions=t),r.renderer){let i=this.defaults.renderer||new ig(this.defaults);for(let o in r.renderer){if(!(o in i))throw new Error(`renderer '${o}' does not exist`);if(["options","parser"].includes(o))continue;let a=o,s=r.renderer[a],c=i[a];i[a]=(...l)=>{let u=s.apply(i,l);return u===!1&&(u=c.apply(i,l)),u||""}}n.renderer=i}if(r.tokenizer){let i=this.defaults.tokenizer||new ng(this.defaults);for(let o in r.tokenizer){if(!(o in i))throw new Error(`tokenizer '${o}' does not exist`);if(["options","rules","lexer"].includes(o))continue;let a=o,s=r.tokenizer[a],c=i[a];i[a]=(...l)=>{let u=s.apply(i,l);return u===!1&&(u=c.apply(i,l)),u}}n.tokenizer=i}if(r.hooks){let i=this.defaults.hooks||new ef;for(let o in r.hooks){if(!(o in i))throw new Error(`hook '${o}' does not exist`);if(["options","block"].includes(o))continue;let a=o,s=r.hooks[a],c=i[a];ef.passThroughHooks.has(o)?i[a]=l=>{if(this.defaults.async&&ef.passThroughHooksRespectAsync.has(o))return(async()=>{let f=await s.call(i,l);return c.call(i,f)})();let u=s.call(i,l);return c.call(i,u)}:i[a]=(...l)=>{if(this.defaults.async)return(async()=>{let f=await s.apply(i,l);return f===!1&&(f=await c.apply(i,l)),f})();let u=s.apply(i,l);return u===!1&&(u=c.apply(i,l)),u}}n.hooks=i}if(r.walkTokens){let i=this.defaults.walkTokens,o=r.walkTokens;n.walkTokens=function(a){let s=[];return s.push(o.call(this,a)),i&&(s=s.concat(i.call(this,a))),s}}this.defaults={...this.defaults,...n}}),this}setOptions(e){return this.defaults={...this.defaults,...e},this}lexer(e,t){return Wr.lex(e,t??this.defaults)}parser(e,t){return ui.parse(e,t??this.defaults)}parseMarkdown(e){return(t,r)=>{let n={...r},i={...this.defaults,...n},o=this.onError(!!i.silent,!!i.async);if(this.defaults.async===!0&&n.async===!1)return o(new Error("marked(): The async option was set to true by an extension. Remove async: false from the parse options object to return a Promise."));if(typeof t>"u"||t===null)return o(new Error("marked(): input parameter is undefined or null"));if(typeof t!="string")return o(new Error("marked(): input parameter is of type "+Object.prototype.toString.call(t)+", string expected"));if(i.hooks&&(i.hooks.options=i,i.hooks.block=e),i.async)return(async()=>{let a=i.hooks?await i.hooks.preprocess(t):t,s=await(i.hooks?await i.hooks.provideLexer(e):e?Wr.lex:Wr.lexInline)(a,i),c=i.hooks?await i.hooks.processAllTokens(s):s;i.walkTokens&&await Promise.all(this.walkTokens(c,i.walkTokens));let l=await(i.hooks?await i.hooks.provideParser(e):e?ui.parse:ui.parseInline)(c,i);return i.hooks?await i.hooks.postprocess(l):l})().catch(o);try{i.hooks&&(t=i.hooks.preprocess(t));let a=(i.hooks?i.hooks.provideLexer(e):e?Wr.lex:Wr.lexInline)(t,i);i.hooks&&(a=i.hooks.processAllTokens(a)),i.walkTokens&&this.walkTokens(a,i.walkTokens);let s=(i.hooks?i.hooks.provideParser(e):e?ui.parse:ui.parseInline)(a,i);return i.hooks&&(s=i.hooks.postprocess(s)),s}catch(a){return o(a)}}}onError(e,t){return r=>{if(r.message+=`
|
|
294
|
+
Please report this to https://github.com/markedjs/marked.`,e){let n="<p>An error occurred:</p><pre>"+Wi(r.message+"",!0)+"</pre>";return t?Promise.resolve(n):n}if(t)return Promise.reject(r);throw r}}},Rs=new w6;tt.options=tt.setOptions=function(e){return Rs.setOptions(e),tt.defaults=Rs.defaults,c0(tt.defaults),tt};tt.getDefaults=RR;tt.defaults=Ns;tt.use=y6;tt.walkTokens=function(e,t){return Rs.walkTokens(e,t)};tt.parseInline=Rs.parseInline;tt.Parser=ui;tt.parser=ui.parse;tt.Renderer=ig;tt.TextRenderer=xR;tt.Lexer=Wr;tt.lexer=Wr.lex;tt.Tokenizer=ng;tt.Hooks=ef;tt.parse=tt;fse=tt.options,pse=tt.setOptions,w0=tt.walkTokens,mse=tt.parseInline,hse=ui.parse,gse=Wr.lex});function k0(e,t){return TR[e][t]}function N0(e,t){return b0[e][t]??A0[e][t]}function OR(e){return R0.get(e.trim().toLocaleLowerCase("en-US"))??null}function A6(e){return ag[e].section}function nf(e,t={}){let r=["outcome","scope","nonGoals","acceptanceExamples"];return t.compact===!1&&r.push("constraints","decisions","openQuestions","verificationExpectations"),r.map(n=>{if(n!=="scope")return`# ${k0(e,n)}
|
|
295
|
+
`;let i=[`# ${k0(e,n)}
|
|
296
|
+
`];return i.push(`## ${A6(e)}
|
|
297
|
+
`),i.push(on(e,`<!-- Add only needed level-three categories (Created, Modified, Deleted, Not created), with paths and responsibilities. Omit unused categories. -->
|
|
298
|
+
`,`<!-- 按实际改动添加三级标题(新建、修改、删除、明确不建),写明路径与职责;无内容的类别可省略。 -->
|
|
299
|
+
`)),i.join(`
|
|
300
|
+
`)}).join(`
|
|
301
|
+
`)}function on(e,t,r){return e==="zh-CN"?r:t}var TR,b0,A0,R0,y0,k6,b6,ag,ul=x(()=>{"use strict";TR={en:{outcome:"Outcome",scope:"Scope",nonGoals:"Non-goals",acceptanceExamples:"Acceptance examples",constraints:"Constraints and invariants",decisions:"Decisions",openQuestions:"Open questions",verificationExpectations:"Verification expectations"},"zh-CN":{outcome:"目标",scope:"范围",nonGoals:"非目标",acceptanceExamples:"验收示例",constraints:"约束与不变量",decisions:"决策",openQuestions:"待解决问题",verificationExpectations:"验证预期"}},b0={en:{verification:"Verification",currentResult:"Current result",acceptance:"Acceptance",checks:"Checks",blockers:"Blockers",risks:"Risks and skipped work",previousIterations:"Previous iterations",conclusion:"Conclusion"},"zh-CN":{verification:"验证",currentResult:"当前结果",acceptance:"验收",checks:"检查",blockers:"阻塞项",risks:"风险与跳过的工作",previousIterations:"之前的迭代",conclusion:"结论"}},A0={en:{acceptanceEvidence:"Acceptance evidence",commandsAndResults:"Commands and results",skippedChecks:"Skipped checks",specConsistency:"Spec consistency",knownLimitationsAndRisks:"Known limitations and risks",conclusion:"Conclusion"},"zh-CN":{acceptanceEvidence:"验收证据",commandsAndResults:"命令与结果",skippedChecks:"跳过的检查",specConsistency:"规格一致性",knownLimitationsAndRisks:"已知限制与风险",conclusion:"结论"}},R0=new Map,y0=new Map,k6=new Set,b6=new Map,ag={en:{section:"Directory structure",subsections:{created:"Created",modified:"Modified",deleted:"Deleted",notCreated:"Not created"}},"zh-CN":{section:"目录结构",subsections:{created:"新建",modified:"修改",deleted:"删除",notCreated:"明确不建"}}};for(let e of Object.keys(TR)){for(let[t,r]of Object.entries(TR[e]))R0.set(r.toLocaleLowerCase("en-US"),t);for(let[t,r]of Object.entries(b0[e]))y0.set(r.toLocaleLowerCase("en-US"),t);for(let[t,r]of Object.entries(A0[e]))y0.set(r.toLocaleLowerCase("en-US"),t)}for(let e of Object.keys(ag)){k6.add(ag[e].section.toLocaleLowerCase("en-US"));for(let[t,r]of Object.entries(ag[e].subsections))b6.set(r.toLocaleLowerCase("en-US"),t)}});import{createHash as R6}from"crypto";function di(e){throw new TypeError(`Value is not valid canonical JSON: ${e}`)}function N6(e,t){t.has(e)&&di("cyclic structures are not supported"),t.add(e);try{let r=Object.keys(e);for(let n=0;n<e.length;n+=1)Object.prototype.hasOwnProperty.call(e,n)||di("sparse arrays are not supported");return(r.length!==e.length||r.some((n,i)=>n!==String(i)))&&di("arrays must not have named enumerable properties"),Object.getOwnPropertySymbols(e).length>0&&di("symbol properties are not supported"),`[${e.map(n=>jR(n,t)).join(",")}]`}finally{t.delete(e)}}function S6(e,t){let r=Object.getPrototypeOf(e);r!==Object.prototype&&r!==null&&di("only plain objects are supported"),t.has(e)&&di("cyclic structures are not supported"),Object.getOwnPropertySymbols(e).length>0&&di("symbol properties are not supported"),t.add(e);try{let n=Object.getOwnPropertyDescriptors(e);return`{${Object.keys(e).sort().map(a=>{let s=n[a];return(!s||!("value"in s))&&di("accessor properties are not supported"),`${JSON.stringify(a)}:${jR(s.value,t)}`}).join(",")}}`}finally{t.delete(e)}}function jR(e,t){if(e===null)return"null";switch(typeof e){case"boolean":return e?"true":"false";case"string":return JSON.stringify(e);case"number":return Number.isFinite(e)||di("numbers must be finite"),JSON.stringify(Object.is(e,-0)?0:e);case"object":return Array.isArray(e)?N6(e,t):S6(e,t);case"bigint":case"function":case"symbol":case"undefined":return di(`${typeof e} values are not supported`)}return di("unsupported value type")}function E6(e){return jR(e,new Set)}function of(e,t){if(e.length===0)throw new TypeError("Canonical hash tag must be non-empty");if(/[\r\n]/u.test(e))throw new TypeError("Canonical hash tag must not contain a line break");return R6("sha256").update(`${e}
|
|
302
|
+
${E6(t)}`).digest("hex")}var sg=x(()=>{"use strict"});function C0(e){let t=/^ {0,3}(#{1,6})[ \t]+(.+?)[ \t]*$/u.exec(e);return t?{level:t[1].length,text:t[2].replace(/[ \t]+#+[ \t]*$/u,"").trim()}:null}function S0(e,t){let r=/^ {0,3}(`{3,}|~{3,})(.*)$/u.exec(e);if(!r)return t;let n=r[1][0];return t===null?{marker:n,length:r[1].length}:n===t.marker&&r[1].length>=t.length&&r[2].trim().length===0?null:t}function E0(e){return e.includes("-->")||e.includes("--!>")}function*cg(e){let t=null,r=!1,n=null,i=new Set(["code","pre","script","style","svg","template"]),o=e.replace(/\r\n?/gu,`
|
|
303
|
+
`),a=0,s=0;for(;a<=o.length;){let c=o.indexOf(`
|
|
304
|
+
`,a),l=c===-1?o.slice(a):o.slice(a,c);if(yield{line:l,body:t===null&&!r&&n===null,index:s},s+=1,t!==null)t=S0(l,t);else if(r)E0(l)&&(r=!1);else if(n!==null)new RegExp(`</${n}\\s*>`,"iu").test(l)&&(n=null);else{let f=S0(l,null);if(f!==null)t=f;else{let d=l.trimStart();if(d.startsWith("<!--")&&!E0(d))r=!0;else{let p=/^<([A-Za-z][A-Za-z0-9-]*)\b[^>]*>/u.exec(d);p&&i.has(p[1].toLowerCase())&&!d.startsWith("</")&&!d.endsWith("/>")&&!new RegExp(`</${p[1]}\\s*>`,"iu").test(d)&&(n=p[1])}}}if(c===-1)break;a=c+1}}function af(e){return e.normalize("NFC").replace(/\s+/gu," ").trim()}function DR(e,t,r,n=[],i="content-hash"){let o=af(r),a=t.replaceAll("\\","/").trim(),s=n.map(af);if(o.length===0)throw new Error(`${e} acceptance criterion must not be empty`);if(a.length===0)throw new Error(`${e} acceptance criterion source must not be empty`);return{id:i==="content-hash"?`acceptance-${of(C6,{kind:e,source:a,context:s,text:o})}`:"",kind:e,source:a,context:s,text:o}}function BR(e,t,r="content-hash"){let n=new Set;for(let i of e){let o=r==="content-hash"?i.id:JSON.stringify([i.kind,i.source,i.context,i.text]);if(n.has(o))throw new Error(`${t} contains duplicate acceptance criteria`);n.add(o)}return e}function _6(e){let t=null,r=null,n=0,i=0;for(let{line:o,body:a,index:s}of cg(e)){i=s+1;let c=a?C0(o):null;c?.level===1&&(OR(c.text)==="acceptanceExamples"?(n+=1,n===1&&(t=s+1)):t!==null&&r===null&&(r=s))}if(n===0||t===null)return null;if(n!==1)throw new Error("Brief must contain exactly one Acceptance examples section");return{start:t,end:r??i}}function _0(e,t="brief.md",r=$R.maxCriteria,n="content-hash"){if(!Number.isSafeInteger(r)||r<0)throw new Error("Native brief acceptance budget is invalid");let i=_6(e);if(i===null)return[];let o=null;for(let{line:l,body:u,index:f}of cg(e)){if(f<i.start||f>=i.end)continue;let d=u?/^( {0,3})[-*+][ \t]+/u.exec(l):null;if(d===null)continue;let p=d[1].length;o=o===null?p:Math.min(o,p)}let a=[],s=null,c=()=>{if(s!==null){if(a.length>=r)throw new Error(`Native acceptance exceeds its ${r}-criterion acceptance budget`);a.push(s)}};for(let{line:l,body:u,index:f}of cg(e)){if(f<i.start||f>=i.end)continue;let d=u?/^( {0,3})[-*+][ \t]+(.*)$/u.exec(l):null;d&&d[1].length===o?(c(),s=[d[2]]):s!==null&&s.push(l)}return c(),BR(a.map(l=>DR("brief-example",t,l.join(`
|
|
305
|
+
`),[],n)),"Brief",n)}function I0(e,t="brief.md",r=$R.maxCriteria,n="content-hash"){if(!Number.isSafeInteger(r)||r<0)throw new Error("Native brief acceptance budget is invalid");let i=new Wr().blockTokens(e.replace(/\r\n?/gu,`
|
|
306
|
+
`)),o=i.flatMap((c,l)=>c.type==="heading"&&OR(c.text)==="acceptanceExamples"?[{index:l,depth:c.depth}]:[]);if(o.length===0)return[];if(o.length!==1)throw new Error("Brief must contain exactly one Acceptance examples section");let a=o[0],s=[];for(let c of i.slice(a.index+1)){if(c.type==="heading"&&c.depth<=a.depth)break;if(c.type==="list")for(let l of c.items){if(s.length>=r)throw new Error(`Native acceptance exceeds its ${r}-criterion acceptance budget`);let u=l.raw.replace(/^ {0,3}(?:[-*+]|\d{1,9}[.)])[ \t]*/u,"");s.push(DR("brief-example",t,u,[],n))}}return BR(s,"Brief",n)}function x0(e,t="spec.md",r=$R.maxCriteria,n="content-hash",i={}){if(!Number.isSafeInteger(r)||r<0)throw new Error("Native specification acceptance budget is invalid");let o=[],a=[],s=null,c=()=>{if(s===null)return;if(o.length>=r)throw new Error(`Native acceptance exceeds its ${r}-criterion acceptance budget`);let l=(i.resolveBriefReferences?s.body:[]).map(u=>/^\s*(?:Acceptance|验收)\s*[::]\s*(.*)$/iu.exec(u)?.[1]).filter(u=>u!==void 0);if(l.some(u=>!/^A[1-9]\d*$/u.test(u)))throw new Error("A Spec acceptance reference must be one brief ID such as A1");if(l.length>1)throw new Error("A Spec scenario may reference only one brief acceptance criterion");o.push({...DR("spec-scenario",t,[s.title,...s.body].join(`
|
|
307
|
+
`),s.context,n),...l[0]===void 0?{}:{briefAcceptanceRef:l[0]}}),s=null};for(let{line:l,body:u}of cg(e)){let f=u?C0(l):null,d=f?/^Scenario\s*:\s*(.*)$/iu.exec(f.text):null;if(d){for(c();a.at(-1)&&a.at(-1).level>=f.level;)a.pop();let p=af(d[1]);if(p.length===0)throw new Error("Scenario title must not be empty");s={level:f.level,title:p,body:[],context:a.map(m=>m.text)}}else if(f){for(s!==null&&f.level<=s.level?c():s!==null&&s.body.push(l);a.at(-1)&&a.at(-1).level>=f.level;)a.pop();a.push(f)}else s!==null&&u&&s.body.push(l)}return c(),BR(o,"Specification",n)}var C6,Ise,$R,P0=x(()=>{"use strict";PR();ul();sg();C6="comet.native.acceptance.v1",Ise=Object.freeze({maxItems:16,maxTextBytes:512,maxContextItems:4,maxContextItemBytes:256,maxFailedCheckIds:16,maxSerializedBytes:32*1024}),$R=Object.freeze({maxCriteria:1024})});import T0 from"node:path";function O0(e,t){if(e.length===0||e!==e.trim()||e.includes("\\")||T0.posix.isAbsolute(e)||/^(?:[A-Za-z]:|~)/u.test(e)||e.split("/").includes("..")||T0.posix.normalize(e)!==e||e==="."||e.endsWith("/"))throw new Error(`${t} must be a normalized change-relative ref`);return e}function x6(e,t){return e.localeCompare(t,"en")}function lg(e){let t=O0(e.briefSource??"brief.md","Native brief source"),r=[...e.specs??[]].sort((s,c)=>x6(s.capability,c.capability));if(new Set(r.map(s=>s.capability)).size!==r.length)throw new Error("Native acceptance sources contain duplicate capabilities");let i=(e.legacyBriefBoundaries?_0:I0)(e.briefMarkdown,t,Number.MAX_SAFE_INTEGER,"none").map(({source:s,text:c})=>({source:s,text:c})),o=i.length;for(let s of r){let c=O0(s.source,`Native spec source for ${s.capability}`);for(let l of x0(s.markdown,c,Number.MAX_SAFE_INTEGER,"none",{resolveBriefReferences:e.resolveBriefReferences===!0})){if(l.briefAcceptanceRef!==void 0){let u=Number(l.briefAcceptanceRef.slice(1))-1;if(!Number.isSafeInteger(u)||u<0||u>=o)throw new Error(`Native Spec references unknown brief acceptance ${l.briefAcceptanceRef}: ${c}`);continue}i.push({source:c,text:l.text})}}let a=new Set;for(let s of i){s.text=af(s.text);let c=s.text;if(a.has(c))throw new Error(`Native acceptance contains a duplicate criterion: ${s.text}`);a.add(c)}if(i.length===0)throw new Error(`Native change must define at least one acceptance criterion. In ${t}, write each criterion as a top-level Markdown list item under Acceptance examples, for example: "- Input hello prints Words: 1." Keep requested tables; a table alone does not create formal acceptance items. Alternatively use complete Scenario: blocks in the target Specs. Add the explicit criteria without changing their meaning, then retry the same Shape step; do not recreate the change.`);return i.map((s,c)=>({id:`A${c+1}`,source:s.source,text:s.text}))}function j0(e){let t=e.map(({id:r})=>r);if(new Set(t).size!==t.length)throw new Error("Native acceptance IDs must be unique");for(let r=0;r<t.length;r+=1)if(!I6.test(t[r])||t[r]!==`A${r+1}`)throw new Error("Native acceptance IDs must be the contiguous sequence A1..An")}var I6,sf=x(()=>{"use strict";P0();I6=/^A[1-9]\d*$/u});import P6 from"node:path";function B6(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function W6(e,t){let r=e instanceof Date?new Date(e.valueOf()):new Date(e);if(Number.isNaN(r.valueOf()))throw new Error(`${t} must be a valid timestamp`);return r.toISOString()}function q6(e,t){if(typeof e!="string")throw new Error(`${t} must be an ISO timestamp`);let r=new Date(e);if(Number.isNaN(r.valueOf())||r.toISOString()!==e)throw new Error(`${t} must be a canonical ISO timestamp`);return e}function L6(e){return e.schema===Bi?pa(e):e.schema===Di?ma(e):li(e)}function V6(e){return P6.posix.normalize(e.replaceAll("\\","/"))}function M6(e){return e.spec_changes.map(t=>t.operation==="remove"?{capability:t.capability,operation:"remove",source:null}:{capability:t.capability,operation:t.operation==="replace"?"modify":"create",source:V6(t.source)})}function F6(e,t){return e==="zh-CN"?t==="shape"?"继续澄清并确认验收项":"重新提交候选实现":t==="shape"?"Continue clarification and confirm acceptance":"Submit a fresh implementation candidate"}function H6(e,t,r){return e==="zh-CN"?`从旧版 ${t} ${r} 状态恢复;旧版 Loop、验证结论和运行记录未继承。`:`Recovered from legacy ${t} ${r} state; prior Loop, verification results, and execution records were not inherited.`}function $0(e){let t=L6(e.state);j0(e.acceptance);let r=t.phase==="shape"||t.approval!=="confirmed"?"shape":"build",n=r==="shape"?0:1,i=W6(e.migratedAt??`${t.created_at}T00:00:00.000Z`,"Native portable migration time"),o=e.acceptance.map(a=>({id:a.id,source:a.source,text:a.text,result:"pending",reason:null}));return M({schema:hs,name:t.name,language:t.language,phase:r,status:"active",state_version:1,brief:"brief.md",spec_changes:M6(t),workspace:e.workspace,loop:{stage:r==="shape"?"shape":"building",goal_cycle:1,iteration:n,attempt:0,retry_epoch:0,failed_iteration_count:0,no_progress_count:0,execution_failure_count:0,previous_unresolved_ids:[],next_action:F6(t.language,r)},acceptance:o,builder_handoff:null,blockers:[],verification:null,history:[{goal_cycle:1,iteration:n,attempt:0,outcome:"recovery",unresolved_ids:o.map(({id:a})=>a),summary:Ct(H6(t.language,t.schema,t.phase)),completed_at:i}],history_overflow:Uc(),verification_result:"pending",verification_report:null,archived:!1,created_at:`${t.created_at}T00:00:00.000Z`})}function WR(e){let t=B6(e,"Native portable migration transaction"),r=Object.keys(t).filter(n=>!T6.has(n));if(r.length>0)throw new Error(`Native portable migration transaction has unknown field(s): ${r.join(", ")}`);if(t.schema!==ug)throw new Error("Unsupported Native portable migration transaction schema");if(typeof t.id!="string"||!j6.test(t.id))throw new Error("Native portable migration transaction id is invalid");if(typeof t.change!="string"||!O6.test(t.change))throw new Error("Native portable migration transaction change is invalid");if(typeof t.fromSchema!="string"||!D6.has(t.fromSchema))throw new Error("Native portable migration transaction fromSchema is invalid");if(typeof t.status!="string"||!$6.has(t.status))throw new Error("Native portable migration transaction status is invalid");return{schema:ug,id:t.id,change:t.change,fromSchema:t.fromSchema,status:t.status,createdAt:q6(t.createdAt,"Native portable migration transaction createdAt")}}function D0(e){switch(WR(e).status){case"prepared":return{action:"commit-portable-yaml",fromStatus:"prepared",nextStatus:"yaml-committed"};case"yaml-committed":return{action:"cleanup-legacy-runtime",fromStatus:"yaml-committed",nextStatus:"legacy-cleanup"};case"legacy-cleanup":return{action:"commit-transaction",fromStatus:"legacy-cleanup",nextStatus:"committed"};case"committed":return{action:"done",fromStatus:"committed",nextStatus:null}}}var ug,T6,O6,j6,$6,D6,qR=x(()=>{"use strict";Xd();sf();Se();io();Jc();zd();ug="comet.native.portable-migration.v1",T6=new Set(["schema","id","change","fromSchema","status","createdAt"]),O6=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,j6=/^[a-z0-9][a-z0-9-]{7,127}$/u,$6=new Set(["prepared","yaml-committed","legacy-cleanup","committed"]),D6=new Set([Bi,Di,si])});import VR from"node:path";function L0(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function V0(e,t,r){let n=Object.keys(e).filter(i=>!t.has(i));if(n.length>0)throw new Error(`${r} has unknown field(s): ${n.join(", ")}`)}function LR(e,t){if(e!==void 0){if(e===null)return null;if(typeof e!="string"||!/^[a-f0-9]{64}$/iu.test(e))throw new Error(`${t} must be a SHA-256 hash or null`);return e.toLowerCase()}}function B0(e,t){if(e!==void 0){if(e!==null&&typeof e!="string")throw new Error(`${t} must be text or null`);return e}}function X6(e,t){let r=`Native portable Archive spec_changes[${t}]`,n=L0(e,r);if(V0(n,Y6,r),typeof n.capability!="string"||!q0.test(n.capability))throw new Error(`${r}.capability is invalid`);if(!["create","modify","remove"].includes(String(n.operation)))throw new Error(`${r}.operation is invalid`);let i=n.operation,o=n.delta_source;if(o!==void 0&&(typeof o!="string"||o.length===0||o.includes("\\")||o.startsWith("/")||/^[A-Za-z]:/u.test(o)||o.split("/").some(d=>d==="."||d==="..")))throw new Error(`${r}.delta_source is invalid`);let a=LR(n.base_hash,`${r}.base_hash`),s=B0(n.delta_content,`${r}.delta_content`),c=B0(n.source_content,`${r}.source_content`),l=LR(n.expected_target_hash,`${r}.expected_target_hash`),u=LR(n.result_hash,`${r}.result_hash`),f=o!==void 0;if(f&&(s==null||c===void 0||c===null))throw new Error(`${r}.delta_source requires delta_content, source_content, and result_hash`);if(!f&&(s!==void 0||c!==void 0))throw new Error(`${r} delta transaction fields require delta_source`);if(f&&nn(s).capability!==n.capability)throw new Error(`${r}.delta_content capability does not match capability`);if(i==="remove"){if(n.source!==null||n.content!==null||o!==void 0||s!==void 0||c!==void 0||u!==void 0)throw new Error(`${r} remove requires source and content null`);return{capability:n.capability,operation:i,source:null,content:null,...a===void 0?{}:{base_hash:a},...l===void 0?{}:{expected_target_hash:l}}}if(typeof n.source!="string"||n.source.length===0||n.source.includes("\\")||n.source.startsWith("/")||/^[A-Za-z]:/u.test(n.source)||n.source.split("/").some(d=>d==="."||d===".."))throw new Error(`${r}.${i} source is invalid`);if(typeof n.content!="string")throw new Error(`${r}.${i} content is invalid`);return{capability:n.capability,operation:i,source:n.source,content:n.content,...o===void 0?{}:{delta_source:o},...a===void 0?{}:{base_hash:a},...s===void 0?{}:{delta_content:s},...c===void 0?{}:{source_content:c},...l===void 0?{}:{expected_target_hash:l},...u===void 0?{}:{result_hash:u}}}function Z6(e){let t=L0(e,"Native portable Archive transaction");if(V0(t,G6,"Native portable Archive transaction"),t.schema!==dg)throw new Error("Unsupported Native portable Archive transaction schema");if(typeof t.id!="string"||!J6.test(t.id))throw new Error("Native portable Archive transaction id is invalid");if(typeof t.change!="string"||!q0.test(t.change))throw new Error("Native portable Archive transaction change is invalid");if(!Number.isSafeInteger(t.start_state_version)||Number(t.start_state_version)<0)throw new Error("Native portable Archive transaction state version is invalid");if(typeof t.archive_ref!="string"||!z6.test(t.archive_ref)||!t.archive_ref.endsWith(`-${t.change}`))throw new Error("Native portable Archive transaction ref is invalid");if(typeof t.status!="string"||!K6.has(t.status))throw new Error("Native portable Archive transaction status is invalid");if(!Array.isArray(t.spec_changes))throw new Error("Native portable Archive transaction spec changes are invalid");let r=t.spec_changes.map(X6);if(new Set(r.map(({capability:i})=>i)).size!==r.length)throw new Error("Native portable Archive transaction capabilities must be unique");if(!Number.isSafeInteger(t.next_spec_index)||Number(t.next_spec_index)<0||Number(t.next_spec_index)>r.length)throw new Error("Native portable Archive transaction spec cursor is invalid");if(typeof t.created_at!="string")throw new Error("Native portable Archive transaction timestamp is invalid");let n=new Date(t.created_at);if(Number.isNaN(n.valueOf())||n.toISOString()!==t.created_at)throw new Error("Native portable Archive transaction timestamp is invalid");return{schema:dg,id:t.id,change:t.change,start_state_version:Number(t.start_state_version),archive_ref:t.archive_ref,status:t.status,next_spec_index:Number(t.next_spec_index),spec_changes:r,created_at:t.created_at}}function dl(e){let t=Q6.exec(e);if(t)return{kind:"archive",change:t[1]};let r=U6.exec(e);return r?{kind:"migration",change:r[1]}:null}function Ss(e,t){let r=`${t.kind==="archive"?"portable-archive":"portable-migration"}-${t.change}.json`,n=dl(r);if(!n||n.kind!==t.kind||n.change!==t.change)throw new Error(`Invalid Native portable transaction change: ${t.change}`);return VR.join(e.transactionsDir,r)}async function cf(e,t){let r=dl(t);if(!r)return null;let n=await Pe({root:e.transactionsDir,ref:t,maxBytes:null,includeHash:!1}),i=JSON.parse(n.text),o=VR.join(e.transactionsDir,t);if(r.kind==="archive"){let s=Z6(i);if(s.change!==r.change)throw new Error(`Native portable transaction filename does not match ${s.change}`);return{kind:"archive",change:r.change,file:o,journal:s}}let a=WR(i);if(a.change!==r.change)throw new Error(`Native portable transaction filename does not match ${a.change}`);return{kind:"migration",change:r.change,file:o,journal:a}}async function Mn(e,t){let r=Ss(e,t);try{return await cf(e,VR.basename(r))}catch(n){if(n.code==="ENOENT")return null;throw n}}function fg(e){return e.kind==="archive"||e.journal.status!=="committed"}var dg,W0,Q6,U6,J6,z6,K6,G6,Y6,q0,Es=x(()=>{"use strict";Er();il();qR();dg="comet.native.archive-transaction.v4",W0="[a-z][a-z0-9]*(?:-[a-z0-9]+)*",Q6=new RegExp(`^portable-archive-(${W0})\\.json$`,"u"),U6=new RegExp(`^portable-migration-(${W0})\\.json$`,"u"),J6=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu,z6=/^\d{4}-\d{2}-\d{2}-[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,K6=new Set(["prepared","specs-applied","state-finalized","report-aligned","moved"]),G6=new Set(["schema","id","change","start_state_version","archive_ref","status","next_spec_index","spec_changes","created_at"]),Y6=new Set(["capability","operation","source","content","delta_source","base_hash","delta_content","source_content","expected_target_hash","result_hash"]),q0=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u});import{createHash as M0}from"node:crypto";import{constants as ga,promises as ve}from"node:fs";import je from"node:path";function er(e,t){let r=je.relative(e,t);return r===""||!je.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${je.sep}`)}function F0(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("Native protected file byte limit must be a positive integer");return e}function fl(e,t){return ot({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function MR(e){return{dev:e.dev,ino:e.ino,birthtimeMs:e.birthtimeMs,ctimeMs:e.ctimeMs,mtimeMs:e.mtimeMs,size:e.size}}function qi(e,t){return ot({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.mtimeMs===t.mtimeMs&&e.size===t.size}async function vo(e,t){let r=await ve.lstat(e);if(!r.isDirectory()||r.isSymbolicLink())throw new Error(`${t} parent must be a real directory: ${e}`);return{path:e,realPath:await ve.realpath(e),dev:r.dev,ino:r.ino,birthtimeMs:r.birthtimeMs}}async function wo(e,t,r){let n=je.resolve(e),i=je.resolve(t);if(!er(n,i))throw new Error(`${r} is outside its managed root`);let o=[await vo(n,r)],a=n;for(let s of je.relative(n,i).split(je.sep).filter(Boolean)){await rt(o,r),a=je.join(a,s);let c=await vo(a,r);if(!er(o[0].realPath,c.realPath))throw new Error(`${r} parent resolves outside its managed root: ${a}`);o.push(c)}return await rt(o,r),o}async function rt(e,t){for(let r of e){let n=await ve.lstat(r.path);if(!n.isDirectory()||n.isSymbolicLink()||!fl(r,n)||await ve.realpath(r.path)!==r.realPath)throw new Error(`${t} parent changed during I/O: ${r.path}`)}}async function e4(e,t,r){let n=[],i=0,o=Buffer.allocUnsafe(t===null?64*1024:Math.min(64*1024,t+1));for(;;){let a=t===null?o.length:t+1-i,{bytesRead:s}=await e.read(o,0,Math.min(o.length,a),null);if(s===0)break;if(i+=s,t!==null&&i>t)throw new Error(`${r} exceeds ${t} bytes`);n.push(Buffer.from(o.subarray(0,s)))}return Buffer.concat(n,i)}async function cr(e){let t=e.maxBytes===null?null:F0(e.maxBytes),r=je.resolve(e.file),n=await wo(e.root,je.dirname(r),e.label),i=await Promise.all((e.forbiddenRoots??[]).map(u=>vo(je.resolve(u),e.label)));await e.hooks?.afterParentChainCaptured?.(),await rt(n,e.label);let o=await ve.lstat(r);if(!o.isFile()||o.isSymbolicLink())throw new Error(`${e.label} must be a regular file`);if(t!==null&&o.size>t)throw new Error(`${e.label} exceeds ${t} bytes`);let a=MR(o),s=await ve.realpath(r);if(!er(n[0].realPath,s))throw new Error(`${e.label} resolves outside its managed root`);if(i.some(u=>er(u.realPath,s)))throw new Error(`${e.label} resolves inside an excluded root`);let c=process.platform==="win32"?ga.O_RDONLY:ga.O_RDONLY|ga.O_NOFOLLOW|ga.O_NONBLOCK,l=await ve.open(r,c);try{let u=await l.stat();await e.hooks?.afterOpen?.();let[f,d]=await Promise.all([ve.lstat(r),ve.realpath(r)]);if(await rt(n,e.label),await rt(i,e.label),!u.isFile()||!f.isFile()||f.isSymbolicLink()||d!==s||!qi(a,u)||!qi(a,f))throw new Error(`${e.label} changed while opening`);await e.hooks?.beforeRead?.();let p=await e4(l,t,e.label);await e.hooks?.beforeFinalCheck?.();let[m,h,g]=await Promise.all([l.stat(),ve.lstat(r),ve.realpath(r)]);if(await rt(n,e.label),await rt(i,e.label),!h.isFile()||h.isSymbolicLink()||g!==s||!qi(a,m)||!qi(a,h))throw new Error(`${e.label} changed while reading`);return{bytes:p,hash:M0("sha256").update(p).digest("hex"),size:p.length}}finally{await l.close()}}async function lf(e){let t=je.resolve(e.file),r=await wo(e.root,je.dirname(t),e.label),n=await Promise.all((e.forbiddenRoots??[]).map(l=>vo(je.resolve(l),e.label)));await e.hooks?.afterParentChainCaptured?.(),await rt(r,e.label);let i=await ve.lstat(t);if(!i.isFile()||i.isSymbolicLink())throw new Error(`${e.label} must be a regular file`);let o=MR(i),a=await ve.realpath(t);if(!er(r[0].realPath,a))throw new Error(`${e.label} resolves outside its managed root`);if(n.some(l=>er(l.realPath,a)))throw new Error(`${e.label} resolves inside an excluded root`);let s=process.platform==="win32"?ga.O_RDONLY:ga.O_RDONLY|ga.O_NOFOLLOW|ga.O_NONBLOCK,c=await ve.open(t,s);try{let l=await c.stat();await e.hooks?.afterOpen?.();let[u,f]=await Promise.all([ve.lstat(t),ve.realpath(t)]);if(await rt(r,e.label),await rt(n,e.label),!l.isFile()||!u.isFile()||u.isSymbolicLink()||f!==a||!qi(o,l)||!qi(o,u))throw new Error(`${e.label} changed while opening`);await e.hooks?.beforeRead?.();let d=M0("sha256"),p=0,m=Buffer.allocUnsafe(64*1024);for(;;){let{bytesRead:w}=await c.read(m,0,m.length,null);if(w===0)break;p+=w,d.update(m.subarray(0,w))}await e.hooks?.beforeFinalCheck?.();let[h,g,v]=await Promise.all([c.stat(),ve.lstat(t),ve.realpath(t)]);if(await rt(r,e.label),await rt(n,e.label),!g.isFile()||g.isSymbolicLink()||v!==a||!qi(o,h)||!qi(o,g))throw new Error(`${e.label} changed while reading`);return{hash:d.digest("hex"),size:p}}finally{await c.close()}}async function yo(e){let t=await wo(e.root,e.directory,e.label),r;if(e.maxEntries===void 0)r=await ve.readdir(e.directory,{withFileTypes:!0});else{let n=F0(e.maxEntries);r=[];let i=await ve.opendir(e.directory);try{for await(let o of i)if(r.push(o),r.length>n)throw new Error(`${e.label} exceeds ${n} entries`)}finally{await i.close().catch(o=>{if(o.code!=="ERR_DIR_CLOSED")throw o})}}return await rt(t,e.label),{entries:r,verify:()=>rt(t,e.label)}}async function pl(e){let t=await wo(e.root,e.directory,e.label);return{verify:()=>rt(t,e.label)}}async function t4(e){let t=je.resolve(e.directory),r=je.resolve(e.quarantine);if(je.dirname(r)!==je.dirname(t)||!er(je.resolve(e.root),r)||r===t)throw new Error(`${e.label} quarantine must be a distinct sibling inside its root`);let n=await wo(e.root,je.dirname(t),e.label),i=await vo(t,e.label);if(!er(n[0].realPath,i.realPath))throw new Error(`${e.label} resolves outside its managed root`);await e.beforeQuarantine?.(),await rt(n,e.label);let o=await ve.lstat(t);if(!o.isDirectory()||o.isSymbolicLink()||!fl(i,o)||await ve.realpath(t)!==i.realPath)throw new Error(`${e.label} changed before quarantine`);try{throw await ve.lstat(r),new Error(`${e.label} quarantine path is occupied`)}catch(s){if(s.code!=="ENOENT")throw s}await ve.rename(t,r),await rt(n,e.label);let a=await ve.lstat(r);if(!a.isDirectory()||a.isSymbolicLink()||!fl(i,a))throw new Error(`${e.label} changed while quarantining`);await e.afterQuarantine?.(r);try{throw await ve.lstat(t),new Error(`${e.label} path was recreated while quarantining`)}catch(s){if(s.code!=="ENOENT")throw s}return{quarantine:r,parentChain:n,identity:i}}async function H0(e){await t4(e)}async function pg(e){let t=je.resolve(e.file),r=await wo(e.root,je.dirname(t),e.label),n=await ve.lstat(t);if(!n.isFile()||n.isSymbolicLink())throw new Error(`${e.label} must be a regular file`);let i=MR(n),o=await ve.realpath(t);if(!er(r[0].realPath,o))throw new Error(`${e.label} resolves outside its managed root`);let a=await cr({root:e.root,file:t,maxBytes:e.maxBytes,label:e.label});if(a.hash!==e.expectedHash||a.size!==e.expectedSize)throw new Error(`${e.label} changed before removal`);let[s,c]=await Promise.all([ve.lstat(t),ve.realpath(t)]);if(!s.isFile()||s.isSymbolicLink()||!qi(i,s)||c!==o)throw new Error(`${e.label} changed while verifying removal`);await e.beforeRemove?.(),await rt(r,e.label);let[l,u]=await Promise.all([ve.lstat(t),ve.realpath(t)]);if(!l.isFile()||l.isSymbolicLink()||!qi(i,l)||u!==o)throw new Error(`${e.label} changed before removal`);await ve.rm(t),await rt(r,e.label)}async function FR(e){let t=je.resolve(e.directory),r=await wo(e.root,je.dirname(t),e.label),n=await vo(t,e.label);if(!er(r[0].realPath,n.realPath))throw new Error(`${e.label} resolves outside its managed root`);await e.beforeRemove?.(),await rt(r,e.label);let i=await ve.lstat(t);if(!i.isDirectory()||i.isSymbolicLink()||!fl(n,i)||await ve.realpath(t)!==n.realPath)throw new Error(`${e.label} changed before removal`);await ve.rmdir(t),await rt(r,e.label)}async function Li(e){let t=je.resolve(e.root),r=je.resolve(e.directory);if(!er(t,r))throw new Error(`${e.label} is outside its managed root`);let n=[await vo(t,e.label)],i=t;for(let o of je.relative(t,r).split(je.sep).filter(Boolean)){await rt(n,e.label),i=je.join(i,o);try{await ve.mkdir(i)}catch(s){if(s.code!=="EEXIST")throw s}let a=await vo(i,e.label);if(!er(n[0].realPath,a.realPath))throw new Error(`${e.label} resolves outside its managed root: ${i}`);n.push(a)}await rt(n,e.label)}async function mg(e){let t=je.resolve(e.root),r=je.resolve(e.source),n=je.resolve(e.target);if(r===n||!er(t,r)||!er(t,n)||er(r,n)||er(n,r))throw new Error(`${e.label} source and target must be distinct paths inside one root`);await Li({root:t,directory:je.dirname(n),label:`${e.label} target parent`});let i=await wo(t,je.dirname(r),e.label),o=await wo(t,je.dirname(n),e.label),a=await vo(r,e.label);if(!er(i[0].realPath,a.realPath))throw new Error(`${e.label} source resolves outside its managed root`);try{throw await ve.lstat(n),new Error(`${e.label} target already exists`)}catch(l){if(l.code!=="ENOENT")throw l}await e.beforeMove?.(),await Promise.all([rt(i,e.label),rt(o,e.label)]);let s=await ve.lstat(r);if(!s.isDirectory()||s.isSymbolicLink()||!fl(a,s)||await ve.realpath(r)!==a.realPath)throw new Error(`${e.label} source changed before move`);await ve.rename(r,n),await Promise.all([rt(i,e.label),rt(o,e.label)]);let c=await ve.lstat(n);if(!c.isDirectory()||c.isSymbolicLink()||!fl(a,c)||!er(i[0].realPath,await ve.realpath(n)))throw new Error(`${e.label} source identity changed while moving`);try{throw await ve.lstat(r),new Error(`${e.label} source was recreated while moving`)}catch(l){if(l.code!=="ENOENT")throw l}}async function Cs(e){let t=await cr({root:e.sourceRoot,file:e.source,maxBytes:e.maxBytes,label:e.label,hooks:e.hooks,forbiddenRoots:e.forbiddenRoots});if(e.expectedHash!==void 0&&t.hash!==e.expectedHash)throw new Error(`${e.label} content changed before copy`);await wx(e.target,t.bytes,{containedRoot:e.targetRoot,exclusive:e.exclusive,beforeCommit:async()=>{if(await e.hooks?.beforeTargetCommit?.(),e.expectedTargetHash===void 0)return;if(e.expectedTargetHash===null){try{await ve.lstat(e.target)}catch(i){if(i.code==="ENOENT")return;throw i}throw new Error(`${e.label} target changed before commit`)}if((await cr({root:e.targetRoot,file:e.target,maxBytes:e.maxBytes,label:`${e.label} existing target`})).hash!==e.expectedTargetHash)throw new Error(`${e.label} target changed before commit`)}});let r=await cr({root:e.targetRoot,file:e.target,maxBytes:e.maxBytes,label:`${e.label} target`});if(r.hash!==t.hash||r.size!==t.size)throw new Error(`${e.label} target could not be verified`);return r}var _s=x(()=>{"use strict";dt();hc()});import{lstatSync as r4,promises as uf}from"fs";import kr from"path";import{TextDecoder as n4}from"util";function df(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function ff(e,t,r){let n=Object.keys(e).filter(i=>!t.has(i));if(n.length>0)throw new Error(`${r} has unknown field(s): ${n.join(", ")}`)}function hl(e){if(typeof e!="string")return!1;let t=new Date(e);return!Number.isNaN(t.valueOf())&&t.toISOString()===e}function HR(e,t){if(typeof e!="string"||e.length===0||kr.isAbsolute(e)||/^(?:[A-Za-z]:|~|[\\/])/u.test(e)||e.split(/[\\/]/u).includes(".."))throw new Error(`${t} must stay inside the Native root`)}function hg(e,t){if(typeof e!="string"||!/^[a-f0-9]{64}$/u.test(e))throw new Error(`${t} must be a SHA-256 hash`)}function Q0(e,t){if(HR(e,t),e.includes("\\")||e!==kr.posix.normalize(e)||e.split("/").includes(".")||e.endsWith("/")||Buffer.byteLength(e,"utf8")>1024)throw new Error(`${t} must be a normalized Native-relative ref`)}function u4(e,t){let r=df(e,`transaction operations[${t}]`);if(ff(r,o4,`transaction operations[${t}]`),typeof r.id!="string"||!/^[a-z0-9][a-z0-9-]*$/u.test(r.id))throw new Error(`transaction operations[${t}].id is invalid`);if(r.type!=="write"&&r.type!=="remove"&&r.type!=="move")throw new Error(`transaction operation ${r.id} has an invalid type`);HR(r.target,`transaction operation ${r.id} target`);for(let n of["source","staged","backup"])r[n]!==void 0&&HR(r[n],`transaction operation ${r.id} ${n}`);if(r.type==="write"){if(r.staged===void 0||r.source!==void 0)throw new Error(`write operation ${r.id} requires staged and forbids source`)}else if(r.type==="remove"){if(r.source!==void 0||r.staged!==void 0)throw new Error(`remove operation ${r.id} forbids source and staged`)}else if(r.source===void 0||r.staged!==void 0||r.backup!==void 0)throw new Error(`move operation ${r.id} requires source and forbids staged and backup`);return r}function wg(e){let t=df(e,"Native Archive transaction journal");if(ff(t,a4,"Native Archive transaction journal"),t.schema!=="comet.native.transaction.v2")throw new Error("Unsupported Native Archive transaction schema");if(typeof t.id!="string"||!/^[a-f0-9-]{8,}$/u.test(t.id))throw new Error("Native Archive transaction id is invalid");if(t.kind!=="archive")throw new Error("Native v2 transaction kind must be archive");if(typeof t.status!="string"||!z0.has(t.status))throw new Error("Native Archive transaction status is invalid");if(typeof t.change!="string"||!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(t.change))throw new Error("Native Archive transaction change name is invalid");if(!hl(t.createdAt))throw new Error("Native Archive transaction createdAt is invalid");if(hg(t.preflightHash,"Native Archive transaction preflightHash"),!Array.isArray(t.operations)||t.operations.length>65)throw new Error("Native Archive transaction operations must be an array");let r=t.operations.map((s,c)=>{let l=df(s,`Archive transaction operations[${c}]`);if(ff(l,s4,`Archive transaction operations[${c}]`),typeof l.id!="string"||!/^[a-z0-9][a-z0-9-]*$/u.test(l.id))throw new Error(`Archive transaction operations[${c}].id is invalid`);if(l.type!=="write"&&l.type!=="remove"&&l.type!=="move")throw new Error(`Archive transaction operation ${l.id} has an invalid type`);Q0(l.target,`Archive transaction operation ${l.id} target`);for(let u of["source","staged","backup"])l[u]!==void 0&&Q0(l[u],`Archive transaction operation ${l.id} ${u}`);if(l.expectedTargetHash!==null&&hg(l.expectedTargetHash,`Archive transaction operation ${l.id} expectedTargetHash`),l.type==="write"){if(l.staged===void 0||l.source!==void 0||l.expectedSourceHash!==void 0)throw new Error(`Archive write operation ${l.id} requires staged and forbids source`);if(hg(l.stagedHash,`Archive write operation ${l.id} stagedHash`),l.expectedTargetHash===null!=(l.backup===void 0))throw new Error(`Archive write operation ${l.id} backup must match target existence`)}else if(l.type==="remove"){if(l.source!==void 0||l.staged!==void 0||l.stagedHash!==void 0||l.expectedSourceHash!==void 0||l.backup===void 0||l.expectedTargetHash===null)throw new Error(`Archive remove operation ${l.id} requires a bound target and backup`)}else{if(l.source===void 0||l.staged!==void 0||l.stagedHash!==void 0||l.backup!==void 0||l.expectedTargetHash!==null)throw new Error(`Archive move operation ${l.id} requires source and an absent target`);hg(l.expectedSourceHash,`Archive move operation ${l.id} expectedSourceHash`)}return l}),n=r.map(s=>s.id);if(new Set(n).size!==n.length)throw new Error("Native Archive transaction operation ids must be unique");let i=`runtime/transactions/${t.id}`,o=r.filter(s=>s.type==="move");if(o.length!==1||o[0].id!=="archive-change"||o[0].source!==`changes/${t.change}`||!new RegExp(`^archive/\\d{4}-\\d{2}-\\d{2}-${t.change}$`,"u").test(o[0].target)||r.at(-1)!==o[0])throw new Error("Native Archive transaction must end with its exact change move");let a=new Set;for(let s of r.slice(0,-1)){if(s.type==="move"||!/^specs\/[a-z][a-z0-9]*(?:-[a-z0-9]+)*\/spec\.md$/u.test(s.target)||a.has(s.target))throw new Error(`Native Archive transaction spec target is invalid: ${s.target}`);if(a.add(s.target),s.staged!==void 0&&!s.staged.startsWith(`${i}/staged/specs/`))throw new Error(`Native Archive transaction staged ref is invalid: ${s.staged}`);if(s.backup!==void 0&&!s.backup.startsWith(`${i}/backups/specs/`))throw new Error(`Native Archive transaction backup ref is invalid: ${s.backup}`)}return{schema:"comet.native.transaction.v2",id:t.id,kind:"archive",status:t.status,change:t.change,createdAt:t.createdAt,preflightHash:t.preflightHash,operations:r}}function UR(e){let t=df(e,"Native transaction journal");if(t.schema==="comet.native.transaction.v2")return wg(t);if(ff(t,i4,"Native transaction journal"),t.schema!=="comet.native.transaction.v1")throw new Error("Unsupported Native transaction schema");if(typeof t.id!="string"||!/^[a-f0-9-]{8,}$/u.test(t.id))throw new Error("Native transaction id is invalid");if(t.kind!=="archive"&&t.kind!=="root-move")throw new Error("Native transaction kind is invalid");if(typeof t.status!="string"||!z0.has(t.status))throw new Error("Native transaction status is invalid");if(typeof t.projectRoot!="string"||!kr.isAbsolute(t.projectRoot)||typeof t.nativeRoot!="string"||!kr.isAbsolute(t.nativeRoot))throw new Error("Native transaction roots must be absolute paths");if(t.change!==void 0&&(typeof t.change!="string"||!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(t.change)))throw new Error("Native transaction change name is invalid");if(!hl(t.createdAt))throw new Error("Native transaction createdAt is invalid");if(!Array.isArray(t.operations))throw new Error("Native transaction operations must be an array");let r=t.operations.map(u4),n=r.map(i=>i.id);if(new Set(n).size!==n.length)throw new Error("Native transaction operation ids must be unique");return{schema:"comet.native.transaction.v1",id:t.id,kind:t.kind,status:t.status,projectRoot:t.projectRoot,nativeRoot:t.nativeRoot,...typeof t.change=="string"?{change:t.change}:{},createdAt:t.createdAt,operations:r}}function Y0(e,t){let r=df(e,`Native transaction event at line ${t}`);if(ff(r,c4,`Native transaction event at line ${t}`),r.sequence!==t)throw new Error(`Native transaction event sequence at line ${t} must be ${t}`);if(!hl(r.timestamp))throw new Error(`Native transaction event timestamp at line ${t} is invalid`);if(typeof r.type!="string"||!K0.has(r.type))throw new Error(`Native transaction event type at line ${t} is invalid`);let n=r.type==="operation-started"||r.type==="operation-completed";if(n&&(typeof r.operationId!="string"||!/^[a-z0-9][a-z0-9-]*$/u.test(r.operationId)||Buffer.byteLength(r.operationId,"utf8")>256)||!n&&r.operationId!==void 0)throw new Error(`Native transaction event operationId at line ${t} is invalid`);return{sequence:r.sequence,timestamp:r.timestamp,type:r.type,...typeof r.operationId=="string"?{operationId:r.operationId}:{}}}function d4(e){if(e.length>24)return!1;let t="0000-00-00T00:00:00.000Z";for(let n=0;n<e.length;n+=1){let i=t[n],o=e[n];if(i==="0"){if(!/[0-9]/u.test(o))return!1}else if(o!==i)return!1}let r=[[5,2,1,12],[8,2,1,31],[11,2,0,23],[14,2,0,59],[17,2,0,59],[20,3,0,999]];for(let[n,i,o,a]of r){if(e.length<=n)continue;let s=e.slice(n,Math.min(n+i,e.length));if(!Array.from({length:a-o+1},(l,u)=>String(o+u).padStart(i,"0")).some(l=>l.startsWith(s)))return!1}return e.length>=10&&!hl(`${e.slice(0,10)}T00:00:00.000Z`)?!1:e.length<24||hl(e)}function ml(e,t){return e.length<t.length&&t.startsWith(e)}function f4(e){let t='","operationId":"';if(ml(e,t))return!0;if(!e.startsWith(t))return!1;let r=e.slice(t.length),n=r.indexOf('"');if(n===-1)return r.length===0||/^[a-z0-9][a-z0-9-]*$/u.test(r);let i=r.slice(0,n);return/^[a-z0-9][a-z0-9-]*$/u.test(i)?ml(r.slice(n),'"}'):!1}function p4(e,t){if(e.length===0)return!1;let r=`{"sequence":${t},"timestamp":"`;if(ml(e,r))return!0;if(!e.startsWith(r))return!1;let n=e.slice(r.length),i=n.slice(0,Math.min(24,n.length));if(!d4(i))return!1;if(n.length<24)return!0;if(!hl(i))return!1;let o='","type":"',a=n.slice(24);if(ml(a,o))return!0;if(!a.startsWith(o))return!1;let s=a.slice(o.length);for(let c of K0){if(ml(s,c))return!0;if(!s.startsWith(c))continue;let l=s.slice(c.length);if(c==="operation-started"||c==="operation-completed"){if(f4(l))return!0}else if(ml(l,'"}'))return!0}return!1}function m4(e,t){if(e.length===0)throw new Error("Blank transaction event line");return Y0(JSON.parse(e),t)}function h4(e){let t=e.split(`
|
|
308
|
+
`),r=t.at(-1)==="";if(r&&t.pop(),t.length>gg)throw new Error(`Native transaction event log exceeds ${gg} events`);let n=[];for(let i=0;i<t.length;i+=1){let o=i+1,a=t[i],s=a.endsWith("\r")?a.slice(0,-1):a,c=!r&&i===t.length-1;try{n.push(m4(s,o))}catch(l){if(c){let u=!1;try{JSON.parse(s),u=!0}catch{}if(!u&&p4(s,o))break}throw new Error(`Invalid Native transaction event at line ${o}`,{cause:l})}}return n}function X0(e){return e.length===0?"":`${e.map(t=>JSON.stringify(t)).join(`
|
|
309
|
+
`)}
|
|
310
|
+
`}function JR(e,t){if(!/^[a-f0-9-]{8,}$/u.test(t))throw new Error(`Invalid Native transaction id: ${t}`);let r=kr.join(e.transactionsDir,t),n=kr.join(e.runtimeDir,"transaction-history",t),i=o=>{try{return r4(o),!0}catch(a){if(a.code==="ENOENT")return!1;throw a}};if(!i(n))return r;if(i(r))throw new Error(`Conflicting active and historical Native transaction: ${t}`);return n}function zR(e,t){let r=/^runtime\/transactions\/([a-f0-9-]{8,})\/(.+)$/u.exec(t);if(!r)return null;let n=JR(e,r[1]),i=kr.resolve(n,...r[2].split("/"));if(!yt(n,i))throw new Error(`Unsafe Native transaction ref: ${t}`);return i}async function pf(e,t){let r=await Hn(e,t);if(r.status!=="committed"&&r.status!=="rolled-back")throw new Error(`Native transaction ${t} is unfinished`);let n=JR(e,t),i=kr.join(e.runtimeDir,"transaction-history",t);n!==i&&(await mg({root:e.runtimeDir,source:n,target:i,label:"Native completed transaction"}),await Bu(kr.dirname(i)),await Bu(e.transactionsDir),await Bu(e.runtimeDir))}function yg(e,t){let r=JR(e,t);return{directory:r,journal:kr.join(r,"transaction.json"),events:kr.join(r,"events.jsonl"),staged:kr.join(r,"staged"),backups:kr.join(r,"backups")}}async function ko(e,t){let r=yg(e,t);return await Promise.all(Object.values(r).map(n=>ft(e.runtimeDir,n))),r}function g4(e,t){if(t.length===0||kr.isAbsolute(t)||/^(?:[A-Za-z]:|~|[\\/])/u.test(t)||t.split(/[\\/]/u).includes(".."))throw new Error(`Unsafe Native transaction ref: ${t}`);let r="runtime/",n=t==="runtime"||t.startsWith(r),i=n?e.runtimeDir:e.nativeRoot,o=t==="runtime"?"":n?t.slice(r.length):t,a=kr.resolve(i,...o.split(/[\\/]/u));if(!yt(i,a))throw new Error(`Unsafe Native transaction ref: ${t}`);return a}async function va(e,t){let r=zR(e,t);if(r)return ft(e.runtimeDir,r);let n=g4(e,t);return ft(Ve(e,n),n)}async function Is(e){try{return await uf.access(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function KR(e,t,r={}){let n=await ko(e,t);try{await uf.lstat(n.events)}catch(i){if(i.code==="ENOENT")return{exists:!1,hash:null,size:0,events:[],canonicalSource:"",needsRepair:!1};throw i}try{let i=await cr({root:e.runtimeDir,file:n.events,maxBytes:null,label:`Native transaction event log ${t}`,hooks:r.hooks}),o;try{o=G0.decode(i.bytes)}catch(c){throw new Error(`Native transaction event log ${t} is not valid UTF-8`,{cause:c})}let a=h4(o),s=X0(a);return{exists:!0,hash:i.hash,size:i.size,events:a,canonicalSource:s,needsRepair:o!==s}}catch(i){throw i.code==="ENOENT"?new Error(`Native transaction event log ${t} changed while reading`,{cause:i}):i}}async function U0(e,t,r){let n=await KR(e,t);if(n.exists!==r.exists||n.hash!==r.hash||n.size!==r.size)throw new Error(`Native transaction event log ${t} changed before append`)}async function Fn(e,t,r,n){let i=await ko(e,t),o=await KR(e,t),a=o.events.find(c=>c.type===r&&c.operationId===n);if(a)return o.needsRepair&&await qe(i.events,o.canonicalSource,{containedRoot:e.runtimeDir,beforeCommit:()=>U0(e,t,o)}),a;if(o.events.length>=gg)throw new Error(`Native transaction event log ${t} exceeds ${gg} events`);let s={sequence:o.events.length+1,timestamp:new Date().toISOString(),type:r,...n?{operationId:n}:{}};return Y0(s,s.sequence),await uf.mkdir(i.directory,{recursive:!0}),await qe(i.events,X0([...o.events,s]),{containedRoot:e.runtimeDir,beforeCommit:()=>U0(e,t,o)}),s}async function Z0(e,t){if(t.schema!=="comet.native.transaction.v1")throw new Error("Native Archive v2 transactions require the content-bound transaction API");t=UR(t);let r=await ko(e,t.id);await uf.mkdir(r.staged,{recursive:!0}),await uf.mkdir(r.backups,{recursive:!0}),await Bt(r.journal,t,{containedRoot:e.runtimeDir}),await Fn(e,t.id,"prepared")}async function Hn(e,t,r={}){let n=await ko(e,t),i=await cr({root:e.runtimeDir,file:n.journal,maxBytes:null,label:`Native transaction journal ${t}`,hooks:r.hooks}),o=JSON.parse(G0.decode(i.bytes)),a=UR(o);if(a.id!==t)throw new Error(`Invalid Native transaction journal: ${t}`);return a}async function xs(e,t,r={}){return(await KR(e,t,r)).events}async function vg(e,t,r){if(t.schema!=="comet.native.transaction.v1")throw new Error("Native Archive v2 transactions require the content-bound transaction API");let n=UR({...t,status:r});return await Bt((await ko(e,t.id)).journal,n,{containedRoot:e.runtimeDir}),(r==="committed"||r==="rolled-back")&&await pf(e,t.id),n}async function QR(e,t,r){try{return await cr({root:Ve(e,t),file:t,maxBytes:null,label:r})}catch(n){if(n.code==="ENOENT")return null;throw n}}async function GR(e,t,r,n){let i=await QR(e,t,`${n} source`);if(!i)throw new Error(`${n} source does not exist`);let o=await QR(e,r,`${n} target`);await Li({root:Ve(e,r),directory:kr.dirname(r),label:`${n} target parent`}),await Cs({sourceRoot:Ve(e,t),source:t,targetRoot:Ve(e,r),target:r,maxBytes:null,label:n,expectedHash:i.hash,expectedTargetHash:o?.hash??null,exclusive:o===null})}async function e$(e,t,r){let n=await QR(e,t,r);n&&await pg({root:Ve(e,t),file:t,maxBytes:null,expectedHash:n.hash,expectedSize:n.size,label:r})}async function J0(e,t){if(!t.backup)return;let r=await va(e,t.target),n=await va(e,t.backup);!await Is(r)||await Is(n)||await GR(e,r,n,`Legacy Native transaction backup ${t.id}`)}async function v4(e,t){let r=await va(e,t.target);if(t.type==="write"){if(!t.staged)throw new Error(`Write operation ${t.id} has no staged ref`);await J0(e,t),await GR(e,await va(e,t.staged),r,`Legacy Native transaction write ${t.id}`);return}if(t.type==="remove"){await J0(e,t),await e$(e,r,`Legacy Native transaction remove ${t.id}`);return}if(!t.source)throw new Error(`Move operation ${t.id} has no source ref`);let n=await va(e,t.source),[i,o]=await Promise.all([Is(n),Is(r)]);if(!i&&o){await(await yo({root:Ve(e,r),directory:r,label:`Legacy Native transaction move target ${t.id}`,maxEntries:l4})).verify();return}if(o)throw new Error(`Move target already exists: ${t.target}`);if(!i)throw new Error(`Move source does not exist: ${t.source}`);await mg({root:Ve(e,n),source:n,target:r,label:`Legacy Native transaction move ${t.id}`})}async function t$(e,t,r){if(t.schema!=="comet.native.transaction.v1")throw new Error("Native Archive v2 transactions require the content-bound transaction API");let n=t.status==="prepared"?await vg(e,t,"applying"):t,i=await xs(e,t.id),o=new Set(i.filter(s=>s.type==="operation-completed").map(s=>s.operationId)),a=o.size;for(let s of n.operations)o.has(s.id)||(await Fn(e,n.id,"operation-started",s.id),await v4(e,s),await Fn(e,n.id,"operation-completed",s.id),a+=1,await r?.afterOperation?.(s,a));return n=await Hn(e,n.id),n}async function w4(e,t){let r=await va(e,t.target),n=t.backup?await va(e,t.backup):null;if(t.type==="move"){if(!t.source)throw new Error(`Move operation ${t.id} has no source ref`);let i=await va(e,t.source);if(await Is(r)){if(await Is(i))throw new Error(`Legacy Native rollback source already exists: ${t.source}`);await mg({root:Ve(e,r),source:r,target:i,label:`Legacy Native transaction rollback move ${t.id}`})}return}n&&await Is(n)?await GR(e,n,r,`Legacy Native transaction rollback restore ${t.id}`):await e$(e,r,`Legacy Native transaction rollback remove ${t.id}`)}async function kg(e,t){if(t.schema!=="comet.native.transaction.v1")throw new Error("Native Archive v2 transactions require the content-bound transaction API");let r=await xs(e,t.id);if(r.some(o=>o.type==="archive-finalization-started"||o.type==="archive-finalized"))throw new Error("An archive whose finalization started can only be recovered by continuing it");let n=await vg(e,t,"rolling-back");await Fn(e,n.id,"rollback-started");let i=new Set(r.filter(o=>o.type==="operation-started"||o.type==="operation-completed").map(o=>o.operationId));for(let o of[...n.operations].reverse())i.has(o.id)&&await w4(e,o);return await Fn(e,n.id,"rollback-completed"),n=await vg(e,n,"rolled-back"),n}async function gl(e,t,r){if(t.schema!=="comet.native.transaction.v1")throw new Error("Native Archive v2 transactions require the content-bound transaction API");return await Fn(e,t.id,r),r==="commit"?vg(e,t,"committed"):t}var i4,o4,a4,s4,c4,z0,K0,gg,l4,G0,vl=x(()=>{"use strict";dt();He();_s();i4=new Set(["schema","id","kind","status","projectRoot","nativeRoot","change","createdAt","operations"]),o4=new Set(["id","type","source","target","staged","backup"]),a4=new Set(["schema","id","kind","status","change","createdAt","preflightHash","operations"]),s4=new Set(["id","type","source","target","staged","backup","expectedSourceHash","expectedTargetHash","stagedHash"]),c4=new Set(["sequence","timestamp","type","operationId"]),z0=new Set(["prepared","applying","committed","rolling-back","rolled-back"]),K0=new Set(["prepared","operation-started","operation-completed","archive-finalization-started","archive-finalized","commit","rollback-started","rollback-completed"]),gg=1024,l4=2e4,G0=new n4("utf-8",{fatal:!0})});import{promises as y4}from"fs";async function k4(e,t,r){let n;try{n=await y4.readdir(e.transactionsDir,{withFileTypes:!0})}catch(i){if(i.code==="ENOENT")return!1;throw i}for(let i of n)if(!(!i.isDirectory()||i.isSymbolicLink()))try{let o=await Hn(e,i.name);if(o.id!==t&&o.status!=="committed"&&o.status!=="rolled-back")return!0;(o.status==="committed"||o.status==="rolled-back")&&await pf(e,o.id)}catch{return!0}for(let i of n)if(dl(i.name))try{let o=await cf(e,i.name);if(!o||r?.kind===o.kind&&r.change===o.change)continue;if(fg(o))return!0}catch{return!0}return!1}async function $e(e,t,r){if(await Nc(e.projectRoot),await k4(e,r?.allowedTransactionId,r?.allowedPortableTransaction))throw new Error("Native transaction recovery is required before another mutation");return t()}var St=x(()=>{"use strict";Et();Es();vl()});import A4 from"node:path";async function bg(e){let t=Nt(e.parent),r=pe(e.paths.projectRoot,t);if(!r)return null;let n=pe(e.paths.projectRoot,e.targetBranch);if(!n)return null;let i=Yt(e.paths.projectRoot).map(a=>A4.resolve(a)).find(a=>ue(a).currentBranch===t);if(!i)return null;let o=Lh({parent:e.parent,targetBranch:e.targetBranch,targetCommit:n,integrationBranch:t,integrationWorktree:i,contract:e.contract});if(r!==n){for(let a of o.children)a.status=a.dependsOn.length===0?"blocked":"pending",a.blocker=a.status==="blocked"?"Supervisor Runtime was lost; portable Child verification evidence is required.":null;o.integration.headCommit=r}return oR(o,{kind:"delivery-reconciled",child:null,runId:null,summary:"Supervisor state rebuilt from Git worktree facts"}),o}var mf=x(()=>{"use strict";it();Sr();Et();St();ai();Oi();rn()});var YR=x(()=>{"use strict";ai();Oi();rn();mf()});import{promises as R4}from"node:fs";import fi from"node:path";function XR(e,t){let r=fi.normalize(fi.resolve(e)),n=fi.normalize(fi.resolve(t));return process.platform==="win32"?r.toLowerCase()===n.toLowerCase():r===n}async function N4(e){let t=Yt(e.projectRoot);t.some(n=>XR(n,e.projectRoot))||t.push(e.projectRoot);let r=[];for(let n of[...new Set(t.map(i=>fi.resolve(i)))]){let i=await Te(n);i&&r.push({projectRoot:n,paths:await we(n,i.native.artifact_root),parent:XR(n,e.projectRoot)})}return r.some(({parent:n})=>n)||r.push({projectRoot:e.projectRoot,paths:e,parent:!0}),r}async function S4(e,t){let r=fi.join(e.paths.changesDir,t,"comet-state.yaml");try{return await Jt(r)}catch(n){if(n.code==="ENOENT")return null;throw n}}async function E4(e,t){let r;try{r=await R4.readdir(e.paths.archiveDir,{withFileTypes:!0})}catch(i){if(i.code==="ENOENT")return[];throw i}let n=[];for(let i of r)if(!(!i.isDirectory()||i.isSymbolicLink()||![...t].some(a=>i.name.endsWith(`-${a}`))))try{let a=fi.join(e.paths.archiveDir,i.name,"comet-state.yaml"),s=await Jt(a);t.has(s.name)&&n.push({file:a,state:s})}catch{}return n}function C4(e,t,r){let n=fi.relative(e.projectRoot,t);if(!n||n===".."||n.startsWith(`..${fi.sep}`))return null;let i=n.split(fi.sep).join("/");try{let o=(0,i$.parseDocument)(te(e.projectRoot,["show",`${r}:${i}`]),{uniqueKeys:!0});return o.errors.length>0?null:M(o.toJS({mapAsMap:!1}))}catch{return null}}function _4(e,t,r){return e.workspace.isolation!=="worktree"||e.workspace.target_branch!==r||e.workspace.finish!==null&&e.workspace.finish!=="merge"?{kind:"blocked",phase:e.phase,projectRoot:t.projectRoot,message:`Native child ${e.name} must use a linked worktree targeting parent branch ${r??"(missing)"}`}:e.status==="blocked"||e.status==="await-user"?{kind:"blocked",phase:e.phase,projectRoot:t.projectRoot,message:e.blockers[0]?.reason.text??`Native child ${e.name} requires user resolution`}:{kind:"active",phase:e.phase,projectRoot:t.projectRoot,message:null}}function n$(e,t){return e.status==="done"&&e.archived&&e.workspace.finish==="merge"&&e.workspace.target_branch===t}async function Ag(e){let t=fi.join(e.paths.changesDir,e.state.name),r=!1,n=null,i;try{i=e.state.children_contract?{contract:e.state.children_contract,size:0,drift:null}:await pn({changeDir:t,validation:fn(e.state),...e.state.acceptance.length>0?{acceptanceIds:e.state.acceptance.map(({id:v})=>v)}:{},policy:"advisory"})}catch(v){n=`Children contract cannot be read; restore children.yaml and confirm Shape: ${v.message}`,i=null}if(!i){let v=await Dr(e.paths,e.state.name,{diagnostics:!0});if(v){let w=Mh(v);return{...w,...r?{coordinationChoiceRequired:!0}:{},confirmed:!1,readyChildren:[],allDone:!1,children:w.children.map(y=>({...y,message:n??"Children contract is missing; restore children.yaml and confirm Shape before continuing"}))}}if(n)throw new Error(n);return e.state.children_contract_ref?{...r?{coordinationChoiceRequired:!0}:{},contractRef:null,confirmed:!1,parentBranch:e.state.workspace.change_branch,children:[],readyChildren:[],allDone:!1}:r?{coordinationChoiceRequired:!0,contractRef:null,confirmed:!1,parentBranch:e.state.workspace.change_branch,children:[],readyChildren:[],allDone:!1}:null}let o=e.state.children_contract_ref??null,a=e.state.workspace.change_branch,s=e.state.phase!=="shape"&&!!e.state.children_contract_ref;if(i.contract.schema===Ho){let v=await Dr(e.paths,e.state.name,{diagnostics:!0});if(!v){let R=e.state.workspace.change_branch??e.state.workspace.target_branch;if(R){let N=await bg({paths:e.paths,parent:e.state.name,targetBranch:R,contract:i.contract});N&&(v=N,await mo(e.paths,N))}}if(v){let R=Mh(v);return s?{...R,schema:i.contract.schema,...r?{coordinationChoiceRequired:!0}:{},contractRef:o,confirmed:s&&R.confirmed}:{...R,schema:i.contract.schema,...r?{coordinationChoiceRequired:!0}:{},contractRef:o,confirmed:!1,readyChildren:[],allDone:!1,children:R.children.map(N=>({...N,message:i.drift?"Children acceptance index is stale; Shape confirmation is required":"Supervisor child plan changed; Shape confirmation is required"}))}}let w=new Map(i.contract.children.map(R=>[R.name,R])),y=i.contract.children.map(R=>({name:R.name,summary:R.summary,dependsOn:[...R.depends_on],covers:[],status:s&&R.depends_on.every(N=>i.contract.children.filter(({name:b})=>b!==R.name).every(({name:b})=>b!==N))?"ready":"pending",phase:null,projectRoot:null,message:s?null:"Parent Shape confirmation is required"}));for(let R of y){if(R.status!=="ready")continue;w.get(R.name).depends_on.length>0&&(R.status="pending")}return{schema:i.contract.schema,...r?{coordinationChoiceRequired:!0}:{},contractRef:o,confirmed:s,parentBranch:a,children:y,readyChildren:y.filter(({status:R})=>R==="ready").map(({name:R})=>R),allDone:!1}}let c=await N4(e.paths),l=new Set(i.contract.children.map(({name:v})=>v)),u=new Map,f=new Map;for(let v of c){let w=v.parent&&a?`refs/heads/${a}`:"HEAD";for(let y of await E4(v,l)){let R={...y,source:v,committedState:C4(v,y.file,w)};u.set(y.state.name,[...u.get(y.state.name)??[],R])}for(let y of l){let R=await S4(v,y);R&&f.set(y,[...f.get(y)??[],{source:v,state:R}])}}let d=new Map;for(let v of i.contract.children){let w=(u.get(v.name)??[]).find(({source:N,committedState:b})=>N.parent&&b?.name===v.name&&n$(b,a));if(w){d.set(v.name,{kind:"done",phase:w.state.phase,projectRoot:w.source.projectRoot,message:null});continue}let y=u.get(v.name)?.[0];if(y){d.set(v.name,{kind:"blocked",phase:y.state.phase,projectRoot:y.source.projectRoot,message:`Native child ${v.name} is archived but not merged into parent branch ${a??"(missing)"}`});continue}let R=f.get(v.name)??[];R.length>1?d.set(v.name,{kind:"blocked",phase:null,projectRoot:null,message:`Native child ${v.name} has multiple active workspace owners`}):R[0]&&d.set(v.name,_4(R[0].state,R[0].source,a))}let p=new Map(i.contract.children.map(v=>[v.name,v])),m=new Map,h=v=>{let w=m.get(v);if(w)return w;let y=p.get(v),N=y.depends_on.map(h).every(({status:G})=>G==="done"),b=d.get(v),E=b?.kind==="active"&&N?y.depends_on.filter(G=>!(u.get(G)??[]).some(({source:Z,committedState:Ae})=>XR(Z.projectRoot,b.projectRoot)&&Ae?.name===G&&n$(Ae,a))):[],I,W=b?.message??null;b?.kind==="done"?(I=N?"done":"blocked",N||(W=`Native child ${v} was merged before its dependencies`)):b?.kind==="active"?(I=N&&E.length===0?"active":"blocked",N?E.length>0&&(W=`Native child ${v} does not include merged dependencies: ${E.join(", ")}`):W=`Native child ${v} started before its dependencies merged`):b?.kind==="blocked"?I="blocked":(I=s&&N?"ready":"pending",s||(W="Parent Shape confirmation is required"));let F={name:v,summary:y.summary,dependsOn:[...y.depends_on],covers:[...y.covers],status:I,phase:b?.phase??null,projectRoot:b?.projectRoot??null,message:W};return m.set(v,F),F},g=i.contract.children.map(({name:v})=>h(v));return{schema:i.contract.schema,...r?{coordinationChoiceRequired:!0}:{},contractRef:o,confirmed:s,parentBranch:a,children:g,readyChildren:g.filter(({status:v})=>v==="ready").map(({name:v})=>v),allDone:g.every(({status:v})=>v==="done")}}var i$,bo=x(()=>{"use strict";i$=dr(Ur(),1);it();Sr();Cr();Et();He();Se();YR();Cr()});import{promises as x4}from"node:fs";import o$ from"node:path";function Mt(e,t){if(!Rg.test(t))throw new Error(`Invalid Native change name: ${t}`);let r=o$.join(e.changesDir,t);if(!yt(e.changesDir,r))throw new Error("Native change path escaped");return r}function Pt(e,t){return o$.join(Mt(e,t),a$)}async function Ps(e,t){try{let r=await x4.readFile(Pt(e,t),"utf8");return/^schema:\s*comet\.native\.v4\s*$/mu.test(r)}catch(r){if(r.code==="ENOENT")return!1;throw r}}function Ng(e,t){let r=ue(t);if(!r.isGitWorktree||r.currentBranch===null||pe(t,r.currentBranch)===null)return null;if(!Vo(t))throw new Error("Native Supervisor Git binding requires a clean current working directory; commit or stash pending changes, then rerun the latest continuation");return{...e,change_branch:r.currentBranch,target_branch:r.currentBranch}}function hf(e,t){if(!t)return;let r=ue(e);if(t.changeBranch!==null&&(!r.isGitWorktree||r.currentBranch!==t.changeBranch))throw new Error(`Native workspace binding ${t.changeBranch??"(missing)"} does not match the current branch ${r.currentBranch??"(detached)"}`);if(t.isolation==="worktree"&&!r.isSecondaryWorktree)throw new Error("Native worktree isolation must use a linked Git worktree")}async function wn(e,t){return Jt(Pt(e,t))}var Rg,a$,Ft=x(()=>{"use strict";Ka();Td();it();Sr();Se();He();Rg=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,a$="comet-state.yaml"});import{promises as c$}from"node:fs";import{AsyncLocalStorage as P4}from"node:async_hooks";import br from"node:path";function qr(e,t,r="active"){if(e!=="native"&&e!=="classic")throw new Error(`Unsupported change workflow: ${e}`);if(!l$.test(t))throw new Error(`Invalid change name: ${t}`);return`${r==="active"?"change-owners":"change-owner-history"}/${e}/${t}.json`}function vf(e,t,r){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Change runtime owner must be a JSON object");let n=e,i=n.schema===pi&&n.workflow===t&&n.change===r,o=n.format==="compat"&&Object.keys(n).length===4,a=n.format==="sdk"&&Object.keys(n).length===6&&n.runId===r&&(typeof n.application=="string"&&/^[a-z][a-z\d]*(?:[.-][a-z\d]+)*$/u.test(n.application)&&!eN.includes(n.application)||(t==="native"?n.application==="native":n.application==="classic-full"||n.application==="classic-hotfix"||n.application==="classic-tweak"));if(!i||!o&&!a)throw new Error(`Invalid change runtime owner for ${t}/${r}`);return n}async function Vi(e,t,r,n){let i;try{({bytes:i}=await Qe(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 ${r}/${n}`)}return vf(o,r,n)}function u$(e){return e.ino<=0n?null:[e.dev,e.ino,e.mode,e.nlink,e.size,e.birthtimeNs,e.mtimeNs,e.ctimeNs].join(":")}function d$(e,t){return qr(e,t),`change-owner-records/${e}/${t}.json`}async function Sg(e,t,r){let n;try{n=await Qe(e,d$(t,r),Number.MAX_SAFE_INTEGER,{label:"canonical change runtime owner",bigint:!0})}catch(o){if(o.code==="ENOENT")return null;throw o}let i;try{i=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(n.bytes))}catch{throw new Error(`Invalid canonical Runtime owner for ${t}/${r}`)}return{owner:vf(i,t,r),identity:u$(n.stat)}}async function f$(e,t,r){let n=await fm(e,"change owner bindings"),i=async s=>{try{let{stat:c}=await n.stat(qr(t,r,s));return u$(c)}catch(c){if(c.code==="ENOENT")return null;throw c}},o=await i("active"),a=await i("history");return await n.finish({allowDirectoryContentChanges:!0}),{active:o,history:a}}async function p$(e,t,r=!1){let n=await f$(e,t.workflow,t.change);if(n.active===null&&n.history===null)return;if(n.active!==null&&n.history!==null)throw new Error(`Conflicting or missing Runtime owner for ${t.workflow}/${t.change}`);let i=r?null:await Sg(e,t.workflow,t.change);if(i?.identity&&i.identity===(n.active??n.history))return;let o=d$(t.workflow,t.change);await $t(e,br.posix.dirname(o),{label:"canonical change runtime owners"});let a=qr(t.workflow,t.change,n.active?"active":"history");try{await hx(br.join(e,a),br.join(e,o),{containedRoot:e})}catch(s){if(!["ENOTSUP","EOPNOTSUPP"].includes(s.code??""))throw s}}async function O4(e,t,r){let n;try{n=await Sg(e,t,r)}catch(o){if(o instanceof ir&&o.reason==="changed")return null;throw o}if(!n?.identity)return null;let i=await f$(e,t,r);return i.active===n.identity&&i.history===null||i.history===n.identity&&i.active===null?n:null}async function g$(e){let t=Ts.getStore();return(t?.active?t.runtimeRoots.get(e):void 0)??T4(e)}async function v$(e,t,r=!1){let n=Ts.getStore();if(n?.active&&e.every(o=>n.roots.has(o)))return t();let i={roots:new Set(e),runtimeRoots:new Map,owners:new Map,projects:new Set,active:!0};try{let o=await Ts.run(i,()=>Ri(()=>r?dm(t):t())),a=m$();for(let s of a.keys())[...i.projects].some(c=>s.startsWith(c+"\0"))&&a.delete(s);for(let[s,c]of i.owners)a.set(s,c);return o}finally{i.active=!1}}async function ZR(e,t,r){let n=await O4(e,t,r);return n?n.owner:v$([e],async()=>{let i=await Vi(e,qr(t,r),t,r),o=await Vi(e,qr(t,r,"history"),t,r);if(i&&o)throw new Error(`Conflicting active and history Runtime owners for ${t}/${r}`);return i??o})}async function Ao(e,t,r,n={}){if(qr(t,r),!n.readOnly)return Ts.run(null,()=>Ri(async()=>ZR(await Ha(e),t,r)));let[i,o]=await g$(e),a=br.parse(i).root,c=(await ie(a,br.relative(a,i).replaceAll("\\","/"),{label:"read-only workspace Runtime",expected:"directory"})).exists?await ZR(i,t,r):null,l=o?await ZR(o,t,r):null;if(c&&l&&JSON.stringify(Object.entries(c).sort())!==JSON.stringify(Object.entries(l).sort()))throw new Error(`Conflicting current and legacy Runtime owners for ${t}/${r}`);return c??l}async function s$(e,t,r,n={}){let i=await Ao(e,t,r,n),o=i?.format==="sdk"?i:null,a=Ts.getStore();return n.readOnly&&a?.active&&a.owners.set(h$(e,t,r),o),o}async function Fe(e,t,r,n={}){if(!n.readOnly||Ts.getStore()?.active)return s$(e,t,r,n);let i=m$(),o=h$(e,t,r);if(i.has(o))return i.get(o);let a=s$(e,t,r,n).catch(s=>{throw i.get(o)===a&&i.delete(o),s});return i.set(o,a),a}async function w$(e,t,r,n=!1){qr(t,"validate");let i=r.readOnly?await g$(e):[await Ha(e)],o=async()=>{let a={active:new Set,history:new Set};for(let s of i)for(let c of["active","history"]){let l=br.parse(s).root,u=br.posix.dirname(qr(t,"validate",c)),f=await ie(l,br.relative(l,br.join(s,u)).replaceAll("\\","/"),{label:`${t} ${c} change runtime owners`,expected:"directory"});if(!f.exists)continue;let d=await c$.readdir(f.target,{withFileTypes:!0});for(let p of d){if(p.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(p.name))continue;if(t==="classic"&&c==="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(p.isFile()&&h.test(p.name)||p.isDirectory()&&/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*\.lock\.contenders$/u.test(p.name))continue}if(!p.name.endsWith(".json"))throw new Error(`Invalid ${t} change runtime owner entry: ${p.name}`);let m=p.name.slice(0,-5);if(!p.isFile()||!l$.test(m))throw new Error(`Invalid ${t} change runtime owner entry: ${p.name}`);a[c].add(m)}}return a};return n?o():v$(i,o)}function gf(e,t){return JSON.stringify(Object.entries(e).sort())===JSON.stringify(Object.entries(t).sort())}async function Eg(e,t,r){return rx(),Ts.run(null,()=>Ri(async()=>{let n=await Cn(e);return qr(t.workflow,t.change),r(n)}))}async function j4(e,t,r){let n=vf(t,t.workflow,t.change);if(n.format!=="sdk"||n.workflow!=="native"||n.application!=="native")throw new Error("Only builtin Native owners can enter or leave history");await Eg(e,n,i=>y$(i,n,r))}async function $4(e,t){let r=br.posix.dirname(t).split("/");for(let n=r.length;n>=0;n-=1){let i=br.join(e,...r.slice(0,n)),o;try{o=await c$.open(i,"r"),await o.sync()}catch(a){if(!["EACCES","EBADF","EINVAL","EISDIR","ENOTSUP","EPERM"].includes(a.code??""))throw a}finally{await o?.close()}}}async function y$(e,t,r,n=!1){let i=t,o=r==="history"?"active":"history",a=qr(t.workflow,t.change,o),s=qr(t.workflow,t.change,r),c=await Vi(e,a,t.workflow,t.change),l=await Vi(e,s,t.workflow,t.change);if(!c&&!l||c&&!gf(c,i)||l&&!gf(l,i))throw new Error(`Change runtime owner identity changed for ${t.workflow}/${t.change}`);l||(await $t(e,br.posix.dirname(s),{label:"change runtime owner directory"}),await Dt(br.join(e,s),`${JSON.stringify(i)}
|
|
311
|
+
`,{containedRoot:e,exclusive:!0,requireAtomicPublication:!0})),await $4(e,s),c&&await Fa(br.join(e,a),{containedRoot:e,beforeRemove:async()=>{let u=await Vi(e,a,t.workflow,t.change),f=await Vi(e,s,t.workflow,t.change);if(!u||!f||!gf(u,i)||!gf(f,i))throw new Error("Change runtime owner changed during partition move")}}),n||await Sg(e,t.workflow,t.change),await p$(e,t,n)}async function Cg(e,t){await j4(e,t,"history")}async function k$(e,t){return Eg(e,{workflow:t,change:"partition-recovery"},async()=>{let r=await w$(e,t,{},!0);return[...new Set([...r.active,...r.history])].sort((n,i)=>n.localeCompare(i,"en"))})}async function _g(e,t,r){return Eg(e,{workflow:t,change:r},async n=>{let i=await Vi(n,qr(t,r),t,r),o=await Vi(n,qr(t,r,"history"),t,r);if(i&&o&&!gf(i,o))throw new Error(`Conflicting active and history Runtime owners for ${t}/${r}`);let a=i??o;if(i&&!o&&(i.format!=="sdk"||i.application!=="native"))return i;if(!a||a.format!=="sdk"||a.workflow!=="native"||a.application!=="native")throw new Error("Only builtin Native owners can be recovered from history");return await y$(n,a,"active",!0),a})}async function b$(e,t,r={}){let n=qr(t.workflow,t.change),i=vf(t,t.workflow,t.change);return Eg(e,i,async o=>{if(await Vi(o,qr(t.workflow,t.change,"history"),t.workflow,t.change))throw new Error(`Change ${t.workflow}/${t.change} is in history; restore its active owner before registering`);await $t(o,br.posix.dirname(n),{label:"change runtime owner directory"});try{await Dt(br.join(o,...n.split("/")),`${JSON.stringify(i)}
|
|
312
|
+
`,{containedRoot:o,exclusive:!0,requireAtomicPublication:!0})}catch(s){if(s.code!=="EEXIST")throw s;let c=await Vi(o,n,t.workflow,t.change);if(JSON.stringify(c)!==JSON.stringify(i))throw new Error(`Change ${t.workflow}/${t.change} is already bound to another Runtime`,{cause:s})}return(r.canonical||await Sg(o,t.workflow,t.change))&&await p$(o,i),i})}function Ro(e,t,r={}){return b$(e,t,r)}function Ig(e,t){return b$(e,t)}var pi,eN,T4,l$,Ts,m$,h$,vle,lr=x(()=>{"use strict";or();Ni();Yn();Xo();lt();or();pi="comet.change-owner.v1",eN=["native","classic-full","classic-hotfix","classic-tweak"],T4=En("changeOwnerRuntimeRoots",e=>Rk(e)),l$=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u;Ts=new P4,m$=to("verifiedOwnerBatchResults",()=>new Map),h$=(e,t,r)=>`${JSON.stringify([e,t])}\0${r}`;vle=En("changeOwnerPartitions",w$)});async function tN(e,t,r){if(!Number.isInteger(t)||t<1)throw new Error("Concurrency must be a positive integer");let n=new Array(e.length),i=0,o=!1,a=async()=>{for(;!o&&i<e.length;){let l=i;i+=1;try{n[l]=await r(e[l],l)}catch(u){throw o=!0,u}}},c=(await Promise.allSettled(Array.from({length:Math.min(t,e.length)},()=>a()))).find(l=>l.status==="rejected");if(c?.status==="rejected")throw c.reason;return n}var rN=x(()=>{"use strict"});import{promises as D4}from"node:fs";import xg from"node:path";async function A$(e){let t=Le(e),r=xg.parse(t).root,n=await ie(r,xg.relative(r,xg.join(t,"change-owner-history/native")),{label:"Native history owners",expected:"directory"});if(!n.exists)return[];let i=(await D4.readdir(n.target,{withFileTypes:!0})).filter(s=>s.name.endsWith(".json")).map(s=>s.name.slice(0,-5)).filter(s=>/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(s)),o=ht({singleWriter:!0,rootDir:xg.join(t,"sdk-runs/native")}),a=await tN(i,4,s=>o.readPartitionMetadata(s).catch(()=>"invalid"));return i.filter((s,c)=>a[c]!=="missing").sort()}var nN=x(()=>{"use strict";lt();Ni();ze();lr();or();rN()});var iN=x(()=>{"use strict"});import{promises as j$}from"node:fs";import K4 from"node:path";function Os(e){throw new A("STORE_INDEX_CORRUPT",e)}async function wl(e,t){let r=await ie(e,`applications/${t}`,{expected:"directory",label:"应用 Store 身份"});if(!r.exists)return null;let n=await j$.lstat(r.target,{bigint:!0});return`${n.dev}:${n.ino}:${n.birthtimeNs}`}async function wf(e){if(!(await ie(e,cN,{expected:"file",label:"工作区应用成员清单"})).exists)return null;try{let{checksum:t,...r}=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode((await Qe(e,cN,Number.MAX_SAFE_INTEGER,{label:"工作区应用成员清单"})).bytes));return(r.schema!==$$||!Array.isArray(r.applications)||!r.applications.every(lN)||new Set(r.applications).size!==r.applications.length||!r.identities||typeof r.identities!="object"||Array.isArray(r.identities)||!r.claims||typeof r.claims!="object"||Array.isArray(r.claims)||Object.keys(r.identities).length!==r.applications.length||Object.keys(r.claims).length!==r.applications.length||r.applications.some(n=>typeof r.identities[n]!="string"||!Array.isArray(r.claims[n])||r.claims[n].some(i=>!i||typeof i.runId!="string"||typeof i.applicationContentHash!="string"||typeof i.actionId!="string"||!Number.isSafeInteger(i.attempt)||typeof i.inputHash!="string"||i.claimToken!==null&&typeof i.claimToken!="string"))||D(r)!==t)&&Os("工作区应用成员清单损坏"),r}catch(t){return Os(`工作区应用成员清单无法读取:${t instanceof Error?t.message:String(t)}`)}}async function dN(e,t){await Dt(K4.join(e,cN),JSON.stringify({...t,checksum:D(t)})+`
|
|
313
|
+
`,{containedRoot:e,requireAtomicPublication:!0})}async function D$(e,t,r,n=!1){let i=await $t(e,"applications",{label:"工作区应用 Store"}),o=await j$.readdir(i,{withFileTypes:!0});!n&&o.some(u=>!lN(u.name)||!u.isDirectory())&&Os("工作区应用分区无法确认;请保留现场并检查,不能忽略可能仍占用资源的应用");let a=o.filter(u=>lN(u.name)&&u.isDirectory()).map(u=>u.name).sort(),s=await wf(e),c=s??{schema:$$,applications:[],identities:{},claims:{}};for(let u of c.applications)n||await wl(e,u)!==c.identities[u]&&Os(`已登记应用 ${u} 的 Store 目录缺失或身份改变;请恢复原目录或完整的 portable checkpoint`);a.includes(t)||(await $t(e,`applications/${t}`,{label:"当前应用 Store"}),a.push(t),a.sort());let l=!s;for(let u of a)c.applications.includes(u)||(c.claims[u]=await r(u),c.identities[u]=await wl(e,u),c.applications.push(u),l=!0);return l&&(c.applications.sort(),await dN(e,c)),c.applications}async function fN(e,t,r,n=!1){if(!r.length)return;let i=await wf(e);(!i||!n&&await wl(e,t)!==i.identities[t])&&Os("领取前必须确认工作区应用成员身份");for(let o of r)i.claims[t].some(a=>uN(a,o))||i.claims[t].push(o);await dN(e,i)}async function B$(e,t,r,n){let i=await wf(e);if(!(!i||await wl(e,t)===i.identities[t]))for(let o of i.claims[t]??[])o.runId===r&&!n.some(a=>uN(o,a))&&Os(`portable checkpoint 缺少原执行身份:${r} / ${o.actionId};必须保留未知执行并核对停止事实`)}async function pN(e,t,r,n=!1){let i=await wf(e);if(!i||!i.applications.includes(t))return;let o=await wl(e,t),a=await r(t);if(o!==i.identities[t]){if((!n||!o)&&Os("工作区应用 Store 身份已改变"),i.claims[t].some(s=>!a.some(c=>uN(s,c))))return;i.identities[t]=o}i.claims[t]=a,await dN(e,i)}async function W$(e,t){let r=await wf(e);if(!r?.applications.includes(t))return!1;try{return await wl(e,t)===r.identities[t]}catch{return!1}}var cN,$$,lN,uN,q$=x(()=>{"use strict";ze();Yn();lt();cN="application-scope-locks/workspace-applications.json",$$="comet.workspace-applications.v1",lN=e=>typeof e=="string"&&/^[a-z][a-z\d]*(?:[.-][a-z\d]+)*$/u.test(e);uN=(e,t)=>e.applicationContentHash===t.applicationContentHash&&e.runId===t.runId&&e.actionId===t.actionId&&e.attempt===t.attempt&&e.inputHash===t.inputHash&&e.claimToken===t.claimToken});function mN(e,t="@"){if(!xe)return hN.then(()=>mN(e,t));let r=e.length+1,n=(xe.__heap_base.value||xe.__heap_base)+4*r-xe.memory.buffer.byteLength;n>0&&xe.memory.grow(Math.ceil(n/65536));let i=xe.sa(r-1);if(typeof Buffer<"u"?Buffer.from(xe.memory.buffer,i,2*(r-1)).write(e,"utf16le"):(G4?X4:Y4)(e,new Uint16Array(xe.memory.buffer,i,r)),!xe.parse())throw Object.assign(new Error(`Parse error ${t}:${e.slice(0,xe.e()).split(`
|
|
314
|
+
`).length}:${xe.e()-e.lastIndexOf(`
|
|
315
|
+
`,xe.e()-1)}`),{idx:xe.e()});let o=[],a=[];for(;xe.ri();){let l=xe.is(),u=xe.ie(),f=xe.it(),d=xe.ai(),p=xe.id(),m=xe.ss(),h=xe.se(),g;xe.ip()&&(g=s(e.slice(p===-1?l-1:l,p===-1?u+1:u)));let v=null;for(v=[],xe.rsa();xe.ra();){let w=xe.aks(),y=xe.ake(),R=xe.avs(),N=xe.ave();v.push([c(e.slice(w,y)),c(e.slice(R,N))])}v.length===0&&(v=null),o.push({n:g,t:f,s:l,e:u,ss:m,se:h,d:p,a:d,at:v})}for(;xe.re();){let l=xe.es(),u=xe.ee(),f=xe.els(),d=xe.ele(),p=f<0?void 0:c(e.slice(f,d)),m=c(e.slice(l,u));a.push({s:l,e:u,ls:f,le:d,ss:xe.ess(),n:m,ln:p})}function s(l){try{return(0,eval)(l)}catch{}}function c(l){if(!l)return l;let u=l[0];return(u==='"'||u==="'")&&s(l)||l}return[o,a,!!xe.f(),!!xe.ms()]}function Y4(e,t){let r=e.length,n=0;for(;n<r;){let i=e.charCodeAt(n);t[n++]=(255&i)<<8|i>>>8}}function X4(e,t){let r=e.length,n=0;for(;n<r;)t[n]=e.charCodeAt(n++)}var Mle,G4,xe,Z4,hN,L$=x(()=>{"use strict";Mle=(function(e){return e[e.Static=1]="Static",e[e.Dynamic=2]="Dynamic",e[e.ImportMeta=3]="ImportMeta",e[e.StaticSourcePhase=4]="StaticSourcePhase",e[e.DynamicSourcePhase=5]="DynamicSourcePhase",e[e.StaticDeferPhase=6]="StaticDeferPhase",e[e.DynamicDeferPhase=7]="DynamicDeferPhase",e})({}),G4=new Uint8Array(new Uint16Array([1]).buffer)[0]===1;Z4=()=>{return e="AGFzbQEAAAABKwhgAAF/YAF/AX9gAABgAn9/AX9gBH9/f38AYAN/f38Bf2ABfwBgA39/fwADPj0CAgEEBAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAgABBQICAgYBAQYBAQEFAQEBAQECAgIBAQEDAQEHAQMDBAUBcAECAgUHAQGCAoCAAgYPAn8BQaCLBAt/AEGgiwQLB80BHgZtZW1vcnkCAAJzYQACAWUABQJpcwAGAmllAAcCc3MACAJzZQAJAml0AAoCYWkACwJpZAAMAmlwAA0CZXMADgJlZQAPA2VscwAQA2VsZQARA2VzcwASAnJpABMCcmUAFAFmABUCbXMAFgJyYQAXA2FrcwAYA2FrZQAZA2F2cwAaA2F2ZQAbA3JzYQAcBXBhcnNlAB0LX19oZWFwX2Jhc2UDAQtfaW5pdGlhbGl6ZQABGV9faW5kaXJlY3RfZnVuY3Rpb25fdGFibGUBAAkHAQBBAQsBAAwBAQrZVz0oAEHYCkGAwAA2AgBB0ApBoIsENgIAQbgKQSo2AgBB1ApBgIAENgIACwQAEAALWQBB6AkgADYCACAAQQF0IgBBADsBoIsEQewJIABBoosEajYCAEHECUEANgIAQdQJQQA2AgBBzAlBADYCAEHICUEANgIAQdwJQQA2AgBB0AlBADYCAEGgiwQLuAEBAn9B7AlB7AkoAgAiBEEoajYCAAJAQdQJKAIAIgVFBEBBxAkgBDYCAAwBCyAFIAQ2AiQLQdQJIAQ2AgBB2AkgBTYCACAEIAA2AgggBEIANwIgIAQgA0EBRiIAOgAYIAQgAzYCFCAEQQA2AhAgBCACNgIEIAQgATYCACAEQQNBAUECIAAbIANBAkYiARs2AhwgBCACIAJBAmpBACAAGyABGzYCDCADQQFrQQFNBEBB8AlBAToAAAsLdwECf0HsCUHsCSgCACIEQRhqNgIAAkBB3AkoAgAiBUUEQEHICSAENgIADAELIAUgBDYCFAtB3AkgBDYCACAEIAM2AgwgBCACNgIIIAQgATYCBCAEIAA2AgBB4AkoAgAhACAEQQA2AhQgBCAANgIQQfAJQQE6AAALCABB9AkoAgALEwBBzAkoAgAoAgBBoIsEa0EBdQscAQF/QcwJKAIAKAIEIgBBoIsEa0EBdUF/IAAbCxMAQcwJKAIAKAIIQaCLBGtBAXULHAEBf0HMCSgCACgCDCIAQaCLBGtBAXVBfyAAGwsLAEHMCSgCACgCHAscAQF/QcwJKAIAKAIQIgBBoIsEa0EBdUF/IAAbCzUBAn9BfyEAAkACQAJAQcwJKAIAKAIUIgFBAWsOAgIBAAsgAUGgiwRrQQF1DwtBfiEACyAACwsAQcwJKAIALQAYCxMAQdAJKAIAKAIAQaCLBGtBAXULEwBB0AkoAgAoAgRBoIsEa0EBdQscAQF/QdAJKAIAKAIIIgBBoIsEa0EBdUF/IAAbCxwBAX9B0AkoAgAoAgwiAEGgiwRrQQF1QX8gABsLEwBB0AkoAgAoAhBBoIsEa0EBdQslAQF/QcwJQcwJKAIAIgBBJGpBxAkgABsoAgAiADYCACAAQQBHCyUBAX9B0AlB0AkoAgAiAEEUakHICSAAGygCACIANgIAIABBAEcLCABB+AktAAALCABB8AktAAALKwEBf0H8CUH8CSgCACIAQRBqQcwJKAIAQSBqIAAbKAIAIgA2AgAgAEEARwsTAEH8CSgCACgCAEGgiwRrQQF1CxMAQfwJKAIAKAIEQaCLBGtBAXULEwBB/AkoAgAoAghBoIsEa0EBdQsTAEH8CSgCACgCDEGgiwRrQQF1CwoAQfwJQQA2AgAL3g8BBn8jAEGA0ABrIgQkAEH4CUEBOgAAQYAIIQBBhApBgAg2AgBBnApBnosEIgJB6AkoAgBBAXRqIgU2AgBB8AlBADoAAEGACkEAOwEAQYIKQQA7AQBBiApBADoAAEH0CUEANgIAQeQJQQA6AABBjAogBEGAEGo2AgBBkAogBDYCAEGUCkEAOgAAA0AgACEBQZgKIAJBAmoiADYCAAJAAkACfwJAAkAgAiAFSQRAIAAvAQAiA0EJa0EFSQ0EAkACQAJAAkACQCADQeUAaw4FAQYGBgIACyADQSBGDQggA0EvRg0DIANBO0YNAgwFC0GCCi8BAA0BIAAQHkUNASACQQRqQYIIQQoQHw0BECBBmAooAgAhAEH4CS0AAA0BQYQKIAA2AgAgACIBIQIMBQsgAi8BBEHtAEcNACAAEB5FDQAgAikABkLwgLyDoI6AOlINABAhQZgKKAIAIQALQYQKIAA2AgAMBgsgAi8BBCIAQSpHBEAgAEEvRw0CECIMBQtBARAjDAQLIAAhAkEAQeQJLQAADQIaDAELQfgJQQA6AAALA0ACQEGYCiACQQJqIgA2AgACQAJAAkACQCACIAVJBEACQAJAAkACQAJAAkACQAJAAkACQAJAIAAvAQAiA0Egaw4QDwgFCAgICAUKAggIAQgIBgALAkACQAJAAkACQAJAIANB2wBrDg8EDQUNDQwNDQMNAQ0NDQIACyADQQlrQQVJDRMgA0H7AGsOAwcMCAwLQYIKLwEADQwgABAeRQ0MIAJBBGpBgghBChAfDQwQIAwRCyACLwEEQe0ARw0LIAAQHkUNCyACKQAGQvCAvIOgjoA6Ug0LECEMEAsgAi8BBEHsAEcNCiAAEB5FDQogAkEGakGyCEEGEB8NCiACLwEMECRFDQpBlApBAToAAAwKC0GCCkGCCi8BACIAQQFqOwEAIARBgBBqIABBA3RqIgBBCDYCACAAIAE2AgQMDgtBggovAQAiAEUND0GCCiAAQQFrOwEADA0LQYAKLwEAIgBFDQxBggovAQAiA0UNDCADQQN0IARqQfgPaigCAEEFRw0MIAQgAEECdGpBBGsoAgAiACgCBA0MIAAgAUECajYCBEGYCiACQQRqNgIAQQEQJRogAEGYCigCACIANgIQQZgKIABBAms2AgAMDAtBggovAQAiAEUNDUGCCiAAQQFrIgM7AQBBgAovAQAiAEUNCyAEQYAQaiADQf//A3FBA3RqKAIAQQVHDQsgBCAAQQJ0akEEaygCACIDKAIERQRAIAMgAUECajYCBAsgAyACQQRqNgIMQYAKIABBAWs7AQAMCwsCQCABLwEAQSlHDQBB1AkoAgAiAEUNACAAKAIMIAFBAmpHDQBB1AlB2AkoAgAiADYCACAABEAgAEEANgIkDAELQcQJQQA2AgALQYIKQYIKLwEAIgBBAWo7AQAgBEGAEGogAEEDdGoiAEEGQQJBlAotAAAbNgIAIAAgATYCBEGUCkEAOgAADAoLQYIKLwEAIgBFDQtBggogAEEBayIAOwEAIARBgBBqIABB//8DcUEDdGooAgBBBEcNCQwICyADECYMCAsCQCACLwEEIgBBKkcEQCAAQS9HDQEQIgwKC0EBECMMCQsCQCABLwEAIgAQJwRAAkACQAJAIABBK2sOBAEKAgAKCyABQQJrLwEAQTBrQf//A3FBCkkNAwwJCyABQQJrLwEAQStGDQIMCAsgAUECay8BAEEtRg0BDAcLIABBKUcNACAEQYAQakGCCi8BAEEDdGooAgQQKA0GCwJAAkBBggovAQAiAkUgAEHmAEdyDQAgBEGAEGogAkEDdGoiA0EIaygCAEEBRw0AIAFBAmsvAQBB7wBHDQEgAUEEaxApRQ0BIANBBGsoAgBBnglBAxAqRQ0BDAcLIABB/QBHDQAgBEGAEGogAkEDdGoiAigCBBArDQYgAigCAEEGRg0GCyABECwNBUGICi0AACAAQS9GcSAAQQBHc0UNBQJAQdwJKAIAIgJFDQAgASACKAIASQ0AIAEgAigCBE0NBgsDQCABQaCLBEsEQEGECiABQQJrIgE2AgAgAS8BACIAEC1FDQELCyAAQf//A3EQLgRAA0AgAUGgiwRLBEBBhAogAUECayIBNgIAIAEvAQAQLg0BCwsgARAvDQYLQYgKQQE6AAAMBwtBggpBggovAQAiAEEBajsBACAEQYAQaiAAQQN0aiIAIAE2AgQgAEEDNgIADAULIANBMGtB//8DcUEKSSADQSByQeEAa0H//wNxQRpJcg0AAkACQCADQdwAaw4EAgEBAgALIANBJEYNAQsgA0GgAUYgA0GAAUlyDQULA0AgAC8BAiIBQSByQeEAayECAkAgAUEwa0H//wNxQQpJIAJB//8DcUEaSXINAAJAAkAgAUHcAGsOBAIBAQIACyABQSRGDQELIAFBoAFGIAFBgAFJcg0GC0GYCiAAQQJqIgA2AgAMAAsAC0GCCkGCCi8BACIAQQFqOwEAIARBgBBqIABBA3RqIgBBATYCACAAIAE2AgQMAwtBgAovAQBFQYIKLwEARUHkCS0AAEF/c3FxDAYLEDBBiApBADoAAAwBCxAxC0GECkGYCigCACIBNgIAC0GYCigCACECDAELCxAyQQALIQMgBEGA0ABqJAAgAw8LIAEhAAtBmAooAgAhAgwACwALFgAgAEGgiwRGBEBBAQ8LIABBAmsQMwtDAQN/AkAgAkUNAANAIAAtAAAiBCABLQAAIgVGBEAgAUEBaiEBIABBAWohACACQQFrIgINAQwCCwsgBCAFayEDCyADC9IIAQV/QZgKQZgKKAIAIgRBDGoiATYCAEHcCSgCACEDQQEQJSECAkACQAJAAkACQAJAIAFBmAooAgAiAEYEQCACEDRFDQELQeAJIAQ2AgACQAJAAkAgAkEqRwRAIAJB+wBHDQFBmAogAEECajYCAEEBECUhAkGcCigCACEBQZgKKAIAIQADQAJAIAJB//8DcSICQSJGIAJBJ0ZyRQRAIAIQNRpBmAooAgAhAgwBCyACECZBmApBmAooAgBBAmoiAjYCAAtBARAlGiAAIAIQNiICQSxGBEBBmApBmAooAgBBAmo2AgBBARAlIQILIAJB/QBGDQMgAEGYCigCACIARg0IIAAgAU0NAAsMBwtBmAogAEECajYCAEEBECUaQZgKKAIAIgAgABA2GgwCC0H4CUEAOgAAAkACQAJAAkACQAJAIAJB4QBrDgwCCAQBCAMICAgICAUACyACQfYARg0EDAcLQZgKIABBDmoiBDYCAAJAAkACQAJAQQEQJUHhAGsOBgAMAgwMAQwLQZgKKAIAIgEpAAJC84Dkg+CNwDFSDQsgAS8BChAuRQ0LQZgKIAFBCmo2AgBBABAlGgtBmAooAgAiA0ECakGiCEEOEB8NCgJAIAMvARAiARAkDQAgAUEoaw4DAAsACwtBmAogA0EQajYCAEEBECUiAUEqRgRAQZgKQZgKKAIAQQJqNgIAQQEQJSEBCyABQShHDQEMCgtBmAooAgAiAykAAkLsgISDsI7AOVINCSADLwEKIgEQJEUgAUH7AEdxDQlBmAogA0EKajYCAEEBECUiAUH7AEYNCQtBmAooAgAhAyABEDUaQZgKKAIAIgEgA00NCCAAIAQgAyABEAQMCgtBmAogAEEKajYCAEEAECUaQZgKKAIAIQALQZgKIABBEGo2AgBBARAlIgBBKkYEQEGYCkGYCigCAEECajYCAEEBECUhAAsMCQsCQCAAKQACQuyAhIOwjsA5Ug0AIAAvAQoQLUUNAEGYCiAAQQpqNgIAQQEQJSEADAkLIABBBGohAAtBmAogAEEGajYCAEGcCigCACEDA0BBARAlIQBBmAooAgAiASADSw0HIAAQNyECQZgKKAIAIgAgAUYNBCACQT1GBEBBARA4IQJBmAooAgAhAAsgAkEsRw0EQZgKIABBAmo2AgAMAAsAC0HwCUEBOgAAQZgKQZgKKAIAQQJqNgIAC0EBECUhAEGYCigCACEBAkAgAEHmAEcNACABQQJqQZwIQQYQHw0AQZgKIAFBCGo2AgAgBEEBECVBABA5IANBFGpByAkgAxshAgNAIAIoAgAiAEUNAiAAQgA3AgggAEEUaiECDAALAAtBmAogAUECazYCAAsPCyAAIQEMAgsgACAEQQBBABAEQZgKIABBDGo2AgAPCxAyDwtBmAogAUECazYCAA8LQZgKKAIAIQEgABA1GiABQZgKKAIAIgAgASAAEARBmAogAEECazYCAAuKCwEKf0GYCkGYCigCACIGQQxqIgk2AgBBARAlIQBBmAooAgAhAgJAAkACQAJAAkACQAJ/IABBLkYEQEGYCiACQQJqNgIAQQEQJSIAQeQARwRAIABB8wBHBEAgAEHtAEcNB0GYCigCACIAQQJqQYwIQQYQHw0HQYQKKAIAIgEQOkUEQCABLwEAQS5GDQgLIAYgBiAAQQhqQQIQAw8LQZgKKAIAIgBBAmpBkghBChAfDQZBhAooAgAiARA6RQRAIAEvAQBBLkYNBwtBmAogAEEMajYCAEEBIQhBBSEEQQEQJSEAQQEMAgtBmAooAgAiACkAAkLlgJiD0IyAOVINBUGECigCACIBEDpFBEAgAS8BAEEuRg0GC0GYCiAAQQpqNgIAQQchBEEBIQVBARAlIQBBASEIQQIMAQsCQAJAIABB8wBHIAIgCU1yRQRAQfMAIQAgAkECakGSCEEKEB8NASACLwEMECRFDQFBmAogAkEMaiIANgIAQQEhCEEBECUhASAAQZgKKAIAIgRHBEBB5gAhACABQeYARwRAQQUhBCABIQBBAQwFC0EBIQMgBEECakGcCEEGEB8NBSAELwEIEC1FDQULQZgKIAI2AgBBByEEQQEhB0EAIQggASEAQQAMAwtBByEEQQEhByAAQeQARyACIAZBCmpNcg0BQeQAIQAgAikAAkLlgJiD0IyAOVINACACLwEKECRFDQBBmAogAkEKajYCAEEqIQBBASEFQQIhA0EBECUiAUEqRg0EQZgKIAI2AgBBACEFIAEhAEEADAILIAIhBAwCC0EACyEDIABBKEYEQEGMCigCAEGCCi8BACIFQQN0aiIAQQU2AgBBggogBUEBajsBACAAQZgKKAIAIgI2AgRBhAooAgAvAQBBLkYNBEGYCiACQQJqNgIAQQEQJSEAIAZBmAooAgAiAUEAIAIQA0HUCSgCACEDIAgEQCADIAQ2AhwLQYAKQYAKLwEAIgRBAWo7AQBBkAooAgAgBEECdGogAzYCAAJAIABBIkYgAEEnRnJFBEACQCAAQeAARw0AQZwKKAIAIQYgASEAA0AgACICIAZPDQECQAJAIABBAmoiAC8BACIHQdwAaw4FAAICAgUBCyACQQRqIQAMAQsgB0EkRw0AIAIvAQRB+wBHDQALC0GYCiABQQJrNgIADwsgABAmQZgKKAIAIQALQZgKIABBAmoiADYCAAJAAkACQEEBECVBKWsOBAECAgACC0GYCkGYCigCAEECajYCAEEBECUaIAMgADYCBEGYCigCACEAIANBAToAGCADIAA2AhAMCAtBggogBTsBACADIAA2AgRBmAooAgAhACADQQE6ABggAyAAQQJqNgIMQYAKIAQ7AQAPC0GYCkGYCigCAEECazYCAA8LIAdFIABB+wBHckUEQEGYCigCACEAQYIKLwEADQZBnAooAgAhAQNAAkACQCAAIAFJBEBBARAlIgBBIkYgAEEnRnINASAAQf0ARw0CQZgKQZgKKAIAQQJqNgIAC0EBECUhAUGYCigCACEAIAFB5gBGBEAgAEECakGcCEEGEB8NBwtBmAogAEEIajYCAEEBECUiAEEiRyAAQSdHcQ0GIAYgAEEAEDkPCyAAECYLQZgKQZgKKAIAQQJqIgA2AgAMAAsACwJAAkAgAEEnaw4EAwEBAwALIABBIkYNAgtBmAooAgAhBAsgBCAJRw0AQZgKIARBAms2AgAPCyAAQSpHIAVxDQJBggovAQANAkGYCigCACEAQZwKKAIAIQIDQCAAIAJPDQEgAC8BACIBQSdHIAFBIkdxBEBBmAogAEECaiIANgIADAEFIAYgASADEDkPCwALAAsQMgsPC0GYCkGYCigCAEECazYCAA8LQZgKIABBAms2AgALQwEDf0GYCigCACEAQZwKKAIAIQIDQAJAIABBAmohASAAIAJPDQAgASEAIAEvAQBBCmsOBAABAQABCwtBmAogATYCAAtwAQR/QZgKKAIAQQJqIQFBnAooAgAhBAJAA0AgASICQQJqIQEgAiAETw0BIAEvAQAhAwJAIABFBEAgA0EqRg0BIANBCmsOBAMCAgMCCyADQSpHDQELIAIvAQRBL0cNAAsgAkEEaiEBC0GYCiABNgIACwsAIABBn4CABBA8C30BBH9BnAooAgAhA0GYCigCACEBA0ACQAJAAkAgAS8BACICQS9GBEAgAS8BAiIBQSpHBEAgAUEvRg0CQS8PCyAAECMMAgsgAARAIAIQJA0CDAMLIAIQLg0BDAILECILQZgKQZgKKAIAIgRBAmoiATYCACADIARLDQELCyACC4YBAQR/QZgKKAIAIQFBnAooAgAhBAJAA0ACQCABIgJBAmohASACIARPDQAgAS8BACIDIABGDQIgA0HcAEcEQCADQQprDgQBAgIBAgsgAkEEaiEBIAIvAQRBDUcNASACQQZqIAEgAi8BBkEKRhshAQwBCwtBmAogATYCABAyDwtBmAogATYCAAtuAQF/AkAgAEEpRyAAQShrQf//A3FBB0lxIABBIWsiAUEFTUEAQQEgAXRBMXEbckUEQCAAQTprIgFB//8DcUElT0K/gICAoAIgAa2Ip0EBcUVyDQELQQEPCyAAQf0ARyAAQfsAa0H//wNxQQRJcQsuAQF/QQEhAQJAIABBlAlBBRAqDQAgAEGeCUEDECoNACAAQaQJQQIQKiEBCyABC28BAX8CfyAALwEAIgEQJCABQSlGciABQf0ARnJFBEBBACABQd0ARw0BGgsDQAJAIABBoIsETQ0AIAEQJEUNACAAQQJrIgAvAQAhAQwBCwtBASABQSlGIAFB3QBGciABQf0ARnINABogARA0QQFzCws+AQJ/AkAgACACQQF0IgJrIgRBAmoiAEGgiwRJDQAgACABIAIQHw0AIABBoIsERgRAQQEPCyAEEDMhAwsgAwuDAQECf0EBIQICQAJAAkACQAJAAkAgAC8BACIBQTtrDgQFBAQBAAsCQCABQeUAaw4EAwQEAgALIAFBKUYNBCABQfkARw0DIABBAmtBsAlBBhAqDwsgAEECay8BAEE9Rg8LIABBAmtBqAlBBBAqDwsgAEECa0G8CUEDECoPC0EAIQILIAILqgMBAn8CQAJAAkACQAJAAkACQAJAAkACQCAALwEAQeQAaw4UAAECCQkJCQMJCQQFCQkGCQcJCQgJCwJAAkAgAEECay8BAEHpAGsOBAAKCgEKCyAAQQRrQbgIQQIQKg8LIABBBGtBvAhBAxAqDwsCQAJAAkAgAEECay8BAEHzAGsOAwABAgoLIABBBGsvAQAiAUHhAEcEQCABQewARw0KIABBBmtB5QAQOw8LIABBBmtB4wAQOw8LIABBBGtBwghBBBAqDwsgAEEEa0HKCEEGECoPCyAAQQJrLwEAQe8ARw0GIABBBGsvAQBB5QBHDQYgAEEGay8BACIBQfAARwRAIAFB4wBHDQcgAEEIa0HWCEEGECoPCyAAQQhrQeIIQQIQKg8LIABBAmtB5ghBBBAqDwtBASECIABBAmsiAEHpABA7DQQgAEHuCEEFECoPCyAAQQJrQeQAEDsPCyAAQQJrQfgIQQcQKg8LIABBAmtBhglBBBAqDwsgAEECay8BACIBQe8ARwRAIAFB5QBHDQEgAEEEa0HuABA7DwsgAEEEa0GOCUEDECohAgsgAgs0AQF/IABBoAFGIABBCWsiAUEXTUEAQQEgAXRBn4CABHEbckUEQCAAEDQgAEEuR3EPC0EBCwsAIABBjYCABBA8C0gBAn8CQCAALwEAIgJB5QBHBEAgAkHrAEcNASAAQQJrQeYIQQQQKg8LIABBAmsvAQBB9QBHDQAgAEEEa0HKCEEGECohAQsgAQvbAQEEf0GYCigCACEAQZwKKAIAIQMDQCAAQQJqIQECQAJAIAAgA08NAAJAAkACQCABLwEAIgJB2wBrDgIBAgALIAEhACACQQprDgQCBAQCAwsCQANAAkAgAUECaiEAIAEgA08NAAJAAkAgAC8BACICQdwAaw4CAAQBCyABQQRqIQEMAgsgACEBIAJBCmsOBAABAQABCwtBmAogADYCABAyQZgKKAIAIQAMBAtBmAogADYCAAwDCyAAQQRqIQAMAgtBmAogATYCABAyDwsgAkEvRw0AC0GYCiAANgIAC94BAQR/QZgKKAIAIQBBnAooAgAhAwJAAkADQAJAIAAiAUECaiEAIAEgA08NAAJAAkACQCAALwEAIgJB3ABrDgUCBAQEAQALIAJBJEcNAyABLwEEQfsARw0DQZgKIAFBBGoiAjYCAEGMCigCAEGCCi8BACIAQQN0aiIBQQQ2AgBBggogAEEBajsBACABIAI2AgQPC0GYCiAANgIAQYIKQYIKLwEAQQFrIgE7AQBBjAooAgAgAUH//wNxQQN0aigCAEEDRw0DDAQLIAFBBGohAAwBCwtBmAogADYCAAsQMgsLMwEBf0HkCUEBOgAAQZgKKAIAIQBBmApBnAooAgBBAmo2AgBB9AkgAEGgiwRrQQF1NgIACz0BAX8Cf0EBIAAvAQAiAUEJa0H//wNxQQVJIAFBgAFyQaABRnINABpBACABEDRFDQAaIAAQOiABQS5HcgsLXgEBfwJAIABB+P8DcUEoRiAAQSFrIgFBBU1BAEEBIAF0QTFxG3JFBEAgAEE6ayIBQf//A3FBJU9Cv4CAgKADIAGtiKdBAXFFcg0BC0EBDwsgAEH7AGtB//8DcUEESQtXAQN/QZgKKAIAIQEDQAJAIABB//8DcSICECQEQCAAIQMMAQsgACEDIAIQNA0AQQAhA0GYCiABQQJqIgI2AgAgAS8BAiEAIAIhASAADQELCyADQf//A3ELpQEBBH8CQEGYCigCACIDLwEAIgVB4QBHBEAgASECIAAhBAwBC0GYCiADQQRqNgIAQQEQJSECQZgKKAIAIQQCQCACQSJGIAJBJ0ZyRQRAIAIQNRpBmAooAgAhAgwBCyACECZBmApBmAooAgBBAmoiAjYCAAtBARAlIQVBmAooAgAhAwsgAyAERwRAIAQgAkEAIAAgACABRiIAG0EAIAEgABsQBAsgBQvTBAEHf0GYCigCACEBAkAgAEHf/wNxQdsARgRAIAEvAQAhBUGYCiABQQJqNgIAQf0AQd0AIAVB+wBGGyEGQQEQJSEDQZwKKAIAIQcDQAJAIAYgA0H//wNxIgJGQZgKKAIAIgEgB0tyDQACQCACQS5HDQAgAS8BAkEuRw0AIAEvAQRBLkcNAEGYCiABQQZqNgIAQQEQJRA3IQMMAgsCQAJ/AkAgBUH7AEYEQAJAIAJBIkYgAkEnRnJFBEAgAkHbAEcNAUEAEDgaQZgKQZgKKAIAQQJqNgIAIAEMBAsgAhAmQZgKQZgKKAIAQQJqNgIAIAEMAwsgASEAIANBMGtB//8DcUEJSw0BA0AgACICQQJqIQAgAi8BAiIDQTBrQf//A3FBCkkNACADQcEAayIEQR5NQQBBASAEdEG/gIGEBHEbDQAgA0HhAGsiBEEXTUEAQQEgBHRBv8CBBHEbDQACQAJAIANBK2sOBAABAAIBCyACLwEAQSByQeUARg0BCwtBmAogADYCACABDAILIAJBLEYEQEGYCiABQQJqNgIAQQEQJSEDDAULIAIQNyECDAILIAIQNRpBmAooAgALIQBBARAlIgJBOkYEQEGYCkGYCigCAEECajYCAEEBECUQNyECDAELIAAgAU0NACABIAAgASAAEAQLIAJBPUYEQEEAEDghAgtBmAooAgAhASACQSxHDQBBmAogAUECajYCAEEBECUhAwwBCwtBmAogAUECajYCAAwBCyAAEDUaQZgKKAIAIgAgAU0NACABIAAgASAAEAQLQQEQJQvgDgEMf0GECkGYCigCACIBNgIAQZAKKAIAIQpBjAooAgAhB0GcCigCACEMQYIKLwEAIQsgASIDIQUCQANAQZgKIAVBAmoiBDYCACAFIAxPBEBBACEIDAILAkACQCAELwEAIgIQLg0AAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQEGCCi8BACIGIAtHDQAgAiEIAkACQCACQSlrDgQcAQEcAAsgAkE7RiACQd0ARnIgAkH9AEZyDRkLIAAgCXFBAUcNAAJAIAJBImsODgsODg4OCxAIDg4HDg4MAAsCQCACQdsAaw4PBQ4GDg4NDg4EDgIODg4DAAsCQCACQfsAaw4DCQ4KAAsgAkEKaw4EGg0NGg0LAkAgAkEiaw4OCg0NDQ0KDwcNDQYNDQsACwJAIAJB2wBrDg8EDQUNDQwNDQMNAQ0NDQIACwJAIAJBCmsOBBcNDRcACyACQfsAaw4DBwwIDAsgBg0MIAQQHkUNDCAFQQRqQYIIQQoQHw0MECAMEgsgBS8BBEHtAEcNCyAEEB5FDQsgBSkABkLwgLyDoI6AOlINCxAhDBELIAUvAQRB7ABHDQogBBAeRQ0KIAVBBmpBsghBBhAfDQogBS8BDBAkRQ0KQZQKQQE6AAAMCgsgByAGQQN0aiIBQQg2AgBBggogBkEBajsBACABIAM2AgQMDwsgBkUND0GCCiAGQQFrOwEADA4LIAZFDQ1BgAovAQAiAUUNDSAHIAZBA3RqQQhrKAIAQQVHDQ0gCiABQQJ0akEEaygCACIBKAIEDQ0gASADQQJqNgIEQZgKIAVBBGo2AgBBARAlGiABQZgKKAIAIgE2AhBBmAogAUECazYCAAwNCyAGRQ0NQYIKIAZBAWsiBDsBAEGACi8BACIBRQ0MIAcgBEH//wNxQQN0aigCAEEFRw0MIAogAUECdGpBBGsoAgAiBCgCBEUEQCAEIANBAmo2AgQLIAQgBUEEajYCDEGACiABQQFrOwEADAwLAkAgAy8BAEEpRw0AQdQJKAIAIgFFDQAgASgCDCADQQJqRw0AQdQJQdgJKAIAIgE2AgAgAQRAIAFBADYCJAwBC0HECUEANgIACyAHIAZBA3RqIgFBBkECQZQKLQAAGzYCAEGCCiAGQQFqOwEAIAEgAzYCBEGUCkEAOgAADAsLIAZFDQtBggogBkEBayIBOwEAIAcgAUH//wNxQQN0aigCAEEERw0KDAkLIAIQJgwJCwJAIAUvAQQiBEEqRwRAIARBL0cNARAiDAwLQQEQIwwLCwJAIAMvAQAiBRAnBEACQAJAAkAgBUEraw4EAQsCAAsLIANBAmsvAQBBMGtB//8DcUEKSQ0DDAoLIANBAmsvAQBBK0YNAgwJCyADQQJrLwEAQS1GDQEMCAsgBUEpRw0AIAcgBkEDdGooAgQQKA0HCwJAAkAgBkUgBUHmAEdyDQAgByAGQQN0aiIBQQhrKAIAQQFHDQAgA0ECay8BAEHvAEcNASADQQRrEClFDQEgAUEEaygCAEGeCUEDECpFDQEMCAsgBUH9AEcNACAHIAZBA3RqIgEoAgQQKw0HIAEoAgBBBkYNBwsgAxAsDQZBiAotAAAgBUEvRnEgBUEAR3NFDQZB3AkoAgAiAUUNBCADIAEoAgBJDQQgAyEEIAMgASgCBE0NBgwFCyAHIAZBA3RqIgEgAzYCBEGCCiAGQQFqOwEAIAFBAzYCAAwGCyACQTBrQf//A3FBCkkgAkEgckHhAGtB//8DcUEaSXINAAJAAkAgAkHcAGsOBAIBAQIACyACQSRGDQELIAJBoAFGIAJBgAFJcg0GCwNAIAQvAQIiAUEgckHhAGshCAJAIAFBMGtB//8DcUEKSSAIQf//A3FBGklyDQACQAJAIAFB3ABrDgQCAQECAAsgAUEkRg0BCyABQaABRiABQYABSXINBwtBmAogBEECaiIENgIADAALAAsgByAGQQN0aiIBQQE2AgBBggogBkEBajsBACABIAM2AgQMBAsgAyEECwNAIARBoIsESwRAIARBAmsiBC8BACIFEC1FDQELCyAFQf//A3EQLgRAA0AgBEGgiwRLBEBBhAogBEECayIENgIAIAQvAQAQLg0BCwsgBBAvDQELQYgKQQE6AAAMAgsQMEGICkEAOgAADAELEDELQYQKQZgKKAIAIgE2AgAMAQsQMgtBACEIQeQJLQAADQMCQCABIANGBEAgAEUNAUGCCi8BACALRiAJcUUNAUEBIQkgASEDQZgKKAIALwEAIghBCmsOBAUCAgUCCyACQS9GBEBBiAotAABBAXMhCQwBC0EBIQkgAkEwa0H//wNxQQpJIAJB3/8DcUHBAGtB//8DcUEaSXIgAkEkRiACQd8ARnJyIAJB/wBLcg0AIAEhAwJAAkAgAkEnaw4DAwEDAAsCQCACQd0Aaw4EAwEBAwALIAJBIkYgAkH9AEZyDQELQQAhCQsgASEDC0GYCigCACEFDAELCyACDwsgCAuvBAEHfyABQSJGIAFBJ0ZyRQRAEDIPC0GYCigCACEDIAEQJiAAIANBAmpBmAooAgBBARADIAIEQEHUCSgCAEEEQQYgAkEBRhs2AhwLQZgKQZgKKAIAQQJqNgIAQQAQJSEAQZgKKAIAIQQCQAJAIABB9wBHDQAgBC8BAkHpAEcNACAELwEEQfQARw0AIAQvAQZB6ABGDQELQZgKIARBAms2AgAPC0GYCiAEQQhqNgIAAkBBARAlQfsARwRADAELQewJKAIAIQNB1AkoAgAhBUGYCigCACIGIQBBACECA0AgAyEBQZgKIABBAmo2AgBBARAlIQBBmAooAgAhBwJAAkACQCAAQSJHBEAgAEEnRw0BQScQJgwCC0EiECYMAQsgABA1IQNBmAooAgAhAAwBC0GYCigCAEECaiEAQZgKIAA2AgBBARAlIQMLIANBOkcEQAwCC0GYCkGYCigCAEECajYCAEEBECUiA0EiRiADQSdGckUEQAwCC0GYCigCACEIIAMQJkHsCSABQRRqIgM2AgBBmAooAgAhCSABQQA2AhAgASAINgIIIAEgADYCBCABIAc2AgAgASAJQQJqIgA2AgwCQCACRQRAIAUgATYCIAwBCyACIAE2AhALQZgKIAA2AgACQEEBECUiAEEsRwRAIABB/QBGDQEMAwtBmApBmAooAgBBAmoiADYCACABIQIMAQsLIAUgBjYCECAFQZgKKAIAQQJqNgIMDwtBmAogBDYCAAstAQF/AkAgAC8BAEEuRw0AIABBAmsvAQBBLkcNACAAQQRrLwEAQS5GIQELIAELNQEBfwJAIABBoIsESQ0AIAAvAQAgAUcNACAAQaCLBEYEQEEBDwsgAEECay8BABAtIQILIAILKQEBfyAAQaABRiAAQQlrIgJBF01BAEEBIAJ0IAFxG3JFBEBBAA8LQQELC8cBAQBBgggLvwF4AHAAbwByAHQAZQB0AGEAbwB1AHIAYwBlAHIAbwBtAHUAbgBjAHQAaQBvAG4AbABhAHMAcwB2AG8AeQBpAGUAZABlAGwAZQBjAG8AbgB0AGkAbgBpAG4AcwB0AGEAbgB0AHkAYgByAGUAYQByAGUAdAB1AHIAZABlAGIAdQBnAGcAZQBhAHcAYQBpAHQAaAByAHcAaABpAGwAZQBmAG8AcgBpAGYAYwBhAHQAYwBmAGkAbgBhAGwAbABlAGwAcw==",typeof Buffer<"u"?Buffer.from(e,"base64"):Uint8Array.from(atob(e),t=>t.charCodeAt(0));var e},hN=WebAssembly.compile(Z4()).then(WebAssembly.instantiate).then(({exports:e})=>{xe=e})});import{existsSync as e3,readFileSync as t3}from"fs";import V$ from"path";import{fileURLToPath as r3}from"url";function n3(){return"0.5.3"}function M$(){return gN===null&&(gN=n3()),gN}var gN,i3,Jle,F$=x(()=>{"use strict";gN=null,i3="@rpamis/comet",Jle=`https://registry.npmjs.org/${i3}/latest`});import{promises as o3}from"node:fs";import a3 from"node:path";function yf(e){return a3.join(e,".comet","current-change.json")}function s3(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function H$(e){return e===null||typeof e=="string"}function c3(e){let t;try{t=JSON.parse(e)}catch(r){throw new Error(`current change selection contains invalid JSON: ${r instanceof Error?r.message:String(r)}`,{cause:r})}if(!s3(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&&!H$(t.branch))throw new Error("legacy current change selection branch must be a string or null");return{selection:{schema:Tg,workflow:"classic",change:t.change,branch:t.branch??null},legacy:!0}}if(t.schema!==Tg)throw new Error(`current change selection schema must be ${Tg}`);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(!H$(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 an(e){let t;try{let n=yf(e),{bytes:i}=await Yo(n,Q$,{label:"current change selection"});t=i.toString("utf8")}catch(n){if(n.code==="ENOENT")return{status:"missing"};throw new Error(`cannot read current change selection: ${n instanceof Error?n.message:String(n)}`,{cause:n})}return{status:"selected",...c3(t)}}async function vN(e){await o3.rm(yf(e),{force:!0})}async function js(e,t,r){let n=await an(e);return n.status!=="selected"||n.selection.workflow!==t||n.selection.change!==r?!1:(await vN(e),!0)}var Tg,Q$,l3,wa=x(()=>{"use strict";Ni();Xo();Tg="comet.selection.v2",Q$=Number.MAX_SAFE_INTEGER;l3=En("readCometCurrentSelection",e=>an(e))});import{promises as U$}from"node:fs";import yl from"node:path";import{createHash as u3}from"node:crypto";function Q(e){throw new A("INVALID_WORKFLOW",`${e};请修正适配契约或恢复已固定的依赖后继续`)}async function ya(e,t={}){let r={},n=async i=>{let o=await U$.readdir(yl.join(e,i),{withFileTypes:!0});for(let a of o.sort((s,c)=>s.name.localeCompare(c.name,"en"))){let s=i?`${i}/${a.name}`:a.name;if(a.isSymbolicLink()&&Q(`依赖不允许符号链接:${s}`),a.isDirectory())await n(s);else if(a.isFile()){let c=await Qe(e,s,16777216,{label:`应用依赖 ${s}`});r[s]=c.bytes.toString("base64")}else Q(`依赖包含非常规文件:${s}`)}};return await n(""),!t.allowEmpty&&Object.keys(r).length===0&&Q("依赖目录为空"),r}function ka(e){return D(Object.fromEntries(Object.entries(e).map(([t,r])=>[t,u3("sha256").update(Buffer.from(r,"base64")).digest("hex")])))}function d3(e){return Object.fromEntries(Object.entries(e).map(([t,r])=>[t,Buffer.from(r,"base64").toString("utf8")]))}function f3(e,t){for(let[l,u]of[[e,"输入"],[t,"输出"]])(!l||typeof l!="object"||Array.isArray(l))&&Q(`${u} 必须提供可检查的 JSON Schema`),l.$async===!0&&Q(`${u} 不支持异步 Schema,请注册实际 SDK 验证器`);let r=JSON.stringify([e,t]),n=kf.get(r);if(n)return n;let[i,o]=JSON.parse(r),a=new J$.Ajv({strict:!0,allErrors:!0}),s=a.compile(i),c={ajv:a,input:s,output:JSON.stringify(i)===JSON.stringify(o)?s:a.compile(o)};return kf.size>=64&&kf.delete(kf.keys().next().value),kf.set(r,c),c}async function p3(e){let t=await U$.realpath(e),r=await ya(t),n=d3(r);n["SKILL.md"]?.trim()||Q(`Skill 缺少真实 SKILL.md:${e}`);for(let[i,o]of Object.entries(n)){if(!i.endsWith(".md"))continue;let a=[];w0(Wr.lex(o),s=>{(s.type==="link"||s.type==="image")&&a.push(s.href)});for(let s of a){if(/^(?:[a-z][a-z\d+.-]*:|#|\/\/)/iu.test(s))continue;let c;try{c=decodeURIComponent(s.split(/[?#]/u)[0])}catch{Q(`Skill 引用路径编码无效:${i} -> ${s}`)}if(!c)continue;let l=yl.posix.normalize(yl.posix.join(yl.posix.dirname(i),c));(l===".."||l.startsWith("../")||yl.posix.isAbsolute(c))&&Q(`Skill 引用越过依赖目录:${i} -> ${s}`),!Object.hasOwn(n,l)&&!Object.keys(n).some(u=>u.startsWith(`${l}/`))&&Q(`Skill 引用资源缺失:${i} -> ${s}`)}}return{root:t,files:n,contentHash:ka(r)}}async function wN(e,t){(!e||typeof e.id!="string"||!e.id.trim()||typeof e.root!="string")&&Q("Skill 依赖缺少身份或目录");let r=await p3(yl.resolve(t,e.root));e.contentHash!==r.contentHash&&Q(`Skill 内容发生漂移:${e.id}`);let n=e.adapter;(!n||!["guidance","action","check","subworkflow"].includes(n.kind)||!["read","write","external"].includes(n.sideEffect)||!["none","user"].includes(n.interaction)||!["self-report","machine-check","independent-review"].includes(n.completion)||!["stop","repair","retry"].includes(n.failure)||!["manual","reconcile"].includes(n.recovery)||typeof n.controlsApproval!="boolean")&&Q(`Skill 适配契约不完整:${e.id}`),(!Array.isArray(n.scope)||!n.scope.length||n.scope.some(s=>typeof s!="string"||!s.trim())||!Array.isArray(n.requiredCapabilities)||n.requiredCapabilities.some(s=>typeof s!="string"||!s.trim()))&&Q(`Skill 缺少范围或宿主能力:${e.id}`),n.kind==="guidance"&&(n.sideEffect!=="read"||n.controlsApproval||n.interaction!=="none")&&Q(`有副作用或审批逻辑的 Skill 不能作为普通指导:${e.id}`),n.sideEffect==="external"&&n.recovery!=="reconcile"&&Q(`外部操作缺少未知结果核对契约:${e.id}`);let i=n.review;(!i||i.status!=="accepted"||!i.reviewedBy?.trim()||i.contentHash!==r.contentHash||!Array.isArray(i.capabilities)||!i.capabilities.length||!Array.isArray(i.effects)||!i.effects.length)&&Q(`Skill 必需能力尚未完成内容适配审查:${e.id}`);for(let s of[...i.capabilities,...i.effects])(!s||!s.excerpt?.trim()||!r.files[s.file]?.includes(s.excerpt))&&Q(`Skill 审查证据与真实文件不匹配:${e.id}`);i.capabilities.some(s=>typeof s.id!="string"||!s.id.trim())&&Q(`Skill 能力证据缺少身份:${e.id}`);let o=f3(n.inputSchema,n.outputSchema),a=(s,c)=>l=>{s(l)||Q(`${e.id} ${c} 不匹配:${o.ajv.errorsText(s.errors)}`)};return{...r,id:e.id,adapter:n,validateInput:a(o.input,"输入"),validateOutput:a(o.output,"输出")}}var J$,kf,kl=x(()=>{"use strict";J$=dr(bh(),1);PR();ze();lt();kf=new Map});import mi from"node:path";import{realpathSync as m3,existsSync as h3}from"node:fs";function yN(e){let t=structuredClone(e),r=n=>{if(!(!n||typeof n!="object"||Object.isFrozen(n))){for(let i of Object.values(n))r(i);Object.freeze(n)}};return r(t),t}function Qn(e){return["running","unknown"].includes(e.status)||e.status==="cancelled"&&e.type!=="invoke_skill"&&!!e.claim&&!e.cancellation&&!e.executionStop}function Og(e,t){let r=(n,i)=>{let o=mi.relative(mi.resolve(n),mi.resolve(i));return!o||!mi.isAbsolute(o)&&o!==".."&&!o.startsWith(".."+mi.sep)};return r(e,t)||r(t,e)}function jg(e,t,r){return e.manifest.bindings.filter(n=>n.workflowId===t.workflow.id&&n.stepId===r.stepId&&n.usage==="action").flatMap(n=>{let i=e.manifest.skills.find(a=>a.id===n.skillId);if(!i||i.adapter.sideEffect==="read")return[];if(i.adapter.sideEffect!=="write")return i.adapter.scope.map(a=>({ref:a,workspace:!1,write:i.adapter.sideEffect==="write"}));let o=e.projectRoot??process.cwd();if(n.workspaceFrom){o=r.input;for(let a of n.workspaceFrom.split("."))o=o&&typeof o=="object"?o[a]:void 0}if(typeof o!="string"||!mi.isAbsolute(o))throw new A("COMMAND_REJECTED","Skill 缺少实际写入工作区");return i.adapter.scope.map(a=>{let s=mi.resolve(o,a),c=s;for(;!h3(c)&&c!==mi.dirname(c);)c=mi.dirname(c);return{ref:mi.resolve(m3(c),mi.relative(c,s)),workspace:!!n.workspaceFrom,write:!0}})})}function bl(e,t,r,n=[]){let i=(a,s)=>jg(e,a,s),o=i(t,r);if(o.length){for(let a of[t,...n.filter(s=>s.runId!==t.runId)])for(let s of a.actions)if((a.runId!==t.runId||s.id!==r.id)&&(Qn(s)||a.runId===t.runId&&s.status==="pending")&&i(a,s).some(c=>o.some(l=>{if(a.runId===t.runId&&c.write&&l.write&&c.workspace!==l.workspace)throw new A("COMMAND_REJECTED","并行写入不能混用声明工作区和默认范围;请为两项工作指定实际工作区");return!c.write||!l.write?l.ref===c.ref:Og(c.ref,l.ref)}))){let c=new A(a.runId===t.runId?"COMMAND_REJECTED":"SCOPE_HELD",`Skill 写入范围存在并行冲突,仍由 Run ${a.runId} 的 ${s.stepId} 占用;请停止原执行或提交真实结果`);throw Object.assign(c,{blockedRunIds:[a.runId]}),c}}}function z$(e,t,r){let n=e.manifest.bindings.filter(a=>a.workflowId===r.workflow.id&&a.stepId===t.stepId&&a.usage==="action"),i=n[0],o=i?e.skills.get(i.skillId):void 0;if(n.length!==1||!i||!o||t.type!=="invoke_skill"||t.ref!==i.skillId)throw new A("EXECUTOR_UNSUPPORTED","Action 未绑定到唯一的真实 Skill");return{binding:i,skill:o}}function Al(e,t,r){let{binding:n,skill:i}=z$(e,t,r);if(i.validateInput(t.input),i.adapter.sideEffect!=="read"){let o=n.authorizationFrom?r.actionContexts[t.id]?.results[n.authorizationFrom]:void 0,a=r.waits.find(s=>s.stepId===n.authorizationFrom&&s.sequence===o?.sequence);if(!o||a?.status!=="resolved"||!a.decision||!(n.authorizationChoices??["approved"]).includes(a.decision.choice)||a.decision.proposalHash!==a.proposalHash||D(o.value)!==D({choice:a.decision.choice,proposal:a.proposal}))throw new A("STALE_PROPOSAL","此工作缺少父流程的当前批准记录")}return{binding:n,skill:i}}function K$(e,t){let r=async(n,i,o)=>{if(!o)throw new A("INVALID_RUN","Skill 执行需要当前 SDK Run");let{binding:a,skill:s}=Al(e,n,o);if(bl(e,o,n),s.adapter.requiredCapabilities.some(c=>!t.capabilities.includes(c)))throw new A("CAPABILITY_REQUIRED","宿主缺少 Skill 必需能力");if(s.adapter.sideEffect==="external"&&!t.reconcile)throw new A("RECONCILIATION_REQUIRED","外部操作没有结果核对适配器,不能执行");if(!await t.authorize({action:n,run:o,binding:a,skill:s,context:i}))throw new A("COMMAND_REJECTED","宿主授权不覆盖此 Skill、范围或副作用")};return{id:t.id,capabilities:t.capabilities,preflight:r,supports:n=>n.type==="invoke_skill"&&e.manifest.bindings.some(i=>i.stepId===n.stepId&&i.skillId===n.ref&&i.usage==="action"),async execute(n,i,o){if(!o)throw new A("INVALID_RUN","Skill 执行需要当前 SDK Run");let{binding:a,skill:s}=z$(e,n,o);return await t.invokeSkill({action:n,run:o,binding:a,skill:s,context:i})}}}var $g=x(()=>{"use strict";ze()});import{randomUUID as G$}from"node:crypto";import{promises as g3}from"node:fs";import $s from"node:path";function bN(e){let t=e.rootDir,r=p=>{throw new A("STORE_INDEX_CORRUPT",p)},n=async p=>{let m=$s.parse(t).root;if(!(await ie(m,$s.relative(m,t).replaceAll("\\","/"),{label:"应用 Store",expected:"directory"})).exists)return null;let h=`${kN}/${p}.json`;if(!(await ie(t,h,{label:"应用存储索引",expected:"file"})).exists)return null;try{let g=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode((await Qe(t,h,Number.MAX_SAFE_INTEGER,{label:"应用存储索引"})).bytes));if(p==="inventory"){let{checksum:v,...w}=g;return v!==D(w)&&r("独立成员清单校验值不一致"),w}return g}catch{return r(`应用存储索引 ${p} 无法读取;请保留现场并显式检查`)}},i=async(p,m)=>{await $t(t,kN,{label:"应用存储索引"}),await Dt($s.join(t,kN,`${p}.json`),JSON.stringify(["index","inventory"].includes(p)?{...m,checksum:D(m)}:m)+`
|
|
316
|
+
`,{containedRoot:t,requireAtomicPublication:!0})},o=async()=>JSON.stringify(await Promise.all(["",".runtime-store-v2",".runtime-store-history"].map(async p=>{let m=await ie(p?t:$s.dirname(t),p||$s.basename(t),{label:"应用存储分区",expected:"directory"});if(!m.exists)return null;let h=await g3.lstat(m.target);return[h.dev,h.ino,h.mtimeMs,h.ctimeMs]})));async function a(){let p=await n("index");if(!p)return null;let{checksum:m,...h}=p;return m!==D(h)&&r("应用存储索引校验值不一致"),h&&(h.schema!==Dg||typeof h.epoch!="string"||!["building","ready"].includes(h.state)||!Array.isArray(h.holders)||h.holders.some(g=>typeof g!="string")||new Set(h.holders).size!==h.holders.length||!Number.isSafeInteger(h.memberCount)||h.memberCount<0||h.pending!==null&&(!h.pending||typeof h.pending.runId!="string"||typeof h.pending.registering!="boolean"))&&r("应用存储索引格式损坏"),h}async function s(p){let m=await n("inventory");return(!m||m.epoch!==p.epoch||!Array.isArray(m.members)||m.members.some(h=>typeof h!="string")||new Set(m.members).size!==m.members.length||m.aborted!==void 0&&(!Array.isArray(m.aborted)||m.aborted.some(h=>typeof h!="string"||m.members.includes(h))||new Set(m.aborted).size!==m.aborted.length)||m.members.length!==p.memberCount||D(m)!==p.inventoryHash)&&r("应用存储成员清单与 epoch/hash 不一致,不能忽略已登记 Run"),m}async function c(p,m){let h=await UA({rootDir:t}),g=[],v=[];for(let w of h){(w.error||!w.runId)&&r(`Run 无法发现:${w.storageKey} (${w.error?.code??"missing identity"})`);let y=w.runId;await e.settle?.(y);let R=await e.read(y);!R&&m?.aborted?.includes(y)&&!m.members.includes(y)||(R||r(`已发现的 Run 正文缺失:${y}`),g.push(y),await e.holds(R)&&v.push(y))}return m?.members.some(w=>!g.includes(w))&&r("已登记 Run 缺失,不能通过重建索引丢弃占用;请恢复原记录"),p.holders=v.sort(),{epoch:p.epoch,members:g.sort(),...m?.aborted?{aborted:m.aborted.filter(w=>!g.includes(w))}:{}}}async function l(){let p=$s.parse(t).root;await $t(p,$s.relative(p,t).replaceAll("\\","/"),{label:"应用 Store"});let m=await a();if(m?.state==="ready")return m;m||(await n("inventory")&&r("成员清单存在但索引缺失,请显式检查,不能静默初始化"),m={schema:Dg,epoch:G$(),state:"building",inventoryHash:null,memberCount:0,holders:[],pending:null,stamps:null},await i("index",m));let h=await n("inventory"),g=await n("repair");g&&g.inventory.epoch===m.epoch&&D(g.inventory)===m.inventoryHash&&h&&D(h)===g.previousHash&&(h=g.inventory),h&&(h.epoch!==m.epoch||!Array.isArray(h.members)||h.members.some(w=>typeof w!="string")||new Set(h.members).size!==h.members.length||m.inventoryHash!==null&&(D(h)!==m.inventoryHash||h.members.length!==m.memberCount))&&r("初始化中的成员清单不匹配");let v=await c(m,h??void 0);return!h&&m.inventoryHash!==null&&D(v)!==m.inventoryHash&&r("初始化期间成员清单发生变化,不能重写并丢弃原成员"),m.inventoryHash=D(v),m.memberCount=v.members.length,await i("index",m),await i("inventory",v),m.state="ready",m.stamps=await o(),await i("index",m),m}async function u(p){if(!p.pending)return;let{runId:m,registering:h}=p.pending;await e.settle?.(m);let g=await e.read(m);if(!g&&!h&&r(`未完成写入的 Run 缺失:${m}`),!g&&h){let v=await s(p),w=await n("registration");(v.members.includes(m)||w?.epoch===p.epoch&&w.previousHash===p.inventoryHash&&w.inventory.members.includes(m))&&r(`注册已提交或已观测到提交,但 Run 已缺失:${m}`)}if(h){let v=await s(p),w=!1;g&&!v.members.includes(m)?(v.members.push(m),v.members.sort(),v.aborted&&(v.aborted=v.aborted.filter(y=>y!==m)),w=!0):!g&&!v.aborted?.includes(m)&&(v.aborted=[...v.aborted??[],m].sort(),w=!0),w&&(await i("registration",{epoch:p.epoch,previousHash:p.inventoryHash,inventory:v}),await i("inventory",v),p.inventoryHash=D(v),p.memberCount=v.members.length)}p.holders=p.holders.filter(v=>v!==m),g&&await e.holds(g)&&p.holders.push(m),p.holders.sort(),p.pending=null,p.stamps=await o(),await i("index",p)}async function f(p){if(!p.pending?.registering)return;let m=await n("registration");if(m?.epoch===p.epoch&&m.previousHash===p.inventoryHash){let h=await n("inventory");h&&D(h)===D(m.inventory)&&(p.inventoryHash=D(h),p.memberCount=h.members.length)}}async function d(){let p=await l();return await f(p),p.pending&&await u(p),p.stamps!==await o()&&r("Store 分区身份已变化,必须显式 audit;不能继续使用占用投影"),p}return{async isAbortedRegistration(p){let m=await a();if(!m||m.state!=="ready"||m.pending)return!1;let h=await s(m);return!h.members.includes(p)&&!!h.aborted?.includes(p)&&await e.read(p)===null},async holders(){let p=await d(),m=[];for(let h of p.holders){await e.settle?.(h);let g=await e.read(h);g||r(`占用 Run 缺失:${h}`),await e.holds(g)&&m.push(g)}return m},async begin(p,m){let h=await d();m&&(await s(h)).members.includes(p)&&r(`已登记 Run 不能作为新记录重建:${p}`),h.pending={runId:p,registering:m},await i("index",h)},async finish(){let p=await a();(!p||p.state!=="ready")&&r("应用存储索引未就绪"),await f(p),await u(p)},async inspect(){try{let p=await a();return!p&&await n("inventory")&&r("成员清单存在但索引缺失"),p}catch(p){let m=await n("inventory");if(!m||typeof m.epoch!="string")throw p;return{schema:Dg,epoch:m.epoch,state:"corrupt",error:{code:"STORE_INDEX_CORRUPT",message:p instanceof Error?p.message:String(p)}}}},async repair(p,m){let h;try{h=await a()}catch(w){if(p!=="rebuild")throw w;h=null}if(!h&&p==="rebuild"){let w=await n("inventory");w&&w.epoch===m&&Array.isArray(w.members)&&w.members.every(y=>typeof y=="string")&&new Set(w.members).size===w.members.length&&(h={schema:Dg,epoch:w.epoch,state:"building",inventoryHash:D(w),memberCount:w.members.length,holders:[],pending:null,stamps:null})}if(!h||h.epoch!==m)throw new A("STORE_INDEX_EPOCH_CHANGED","索引 epoch 已变化,请重新 inspect");await f(h),h.pending&&await u(h);let g=await s(h),v=await c(h,g);return p==="rebuild"&&(h.epoch=G$(),v.epoch=h.epoch),await i("repair",{previousHash:h.inventoryHash,inventory:v}),h.inventoryHash=D(v),h.memberCount=v.members.length,h.state="building",await i("index",h),await i("inventory",v),h.state="ready",h.stamps=await o(),await i("index",h),h}}}var kN,Dg,Y$=x(()=>{"use strict";Yn();lt();ze();kN=".runtime-store-coordination",Dg="comet.application-holder-index.v1"});import v3 from"node:os";import w3 from"node:path";function X$(e,t,r=v3.homedir()){return w3.join(t==="project"?e:r,".comet/applications")}var Z$=x(()=>{"use strict"});import Un from"node:path";function y3(e){return/^[a-z][a-z\d]*(?:[.-][a-z\d]+)*$/u.test(e)||Q("应用身份无效"),e}function eD(e,t){let r=Un.resolve(e,t),n=Un.parse(r).root;return{volume:n,ref:Un.relative(n,r).replaceAll("\\","/")}}async function tD(e,t,r){let n=eD(e,t);return ie(n.volume,n.ref,{expected:r,label:"SDK application installation"})}async function k3(e,t){let r=`${y3(t)}/current.json`;if(!(await tD(e,r,"file")).exists)return null;let n=eD(e,r),{bytes:i}=await Qe(n.volume,n.ref,1024*1024,{label:"SDK application installation"}),o=JSON.parse(i.toString("utf8"));if((o.schema!=="comet.workflow.application.install.v1"||o.id!==t||!o.version?.trim()||!/^[a-f\d]{64}$/u.test(o.contentHash)||o.packageRef!==`${t}/versions/${o.contentHash}`)&&Q("安装记录无效;保留文件并重新预览"),o.entry){let a=Un.dirname(Un.dirname(e)),s=Un.dirname(o.entry.root??"");(!Un.isAbsolute(o.entry.root)||![Un.join(a,".claude/skills"),Un.join(a,".agents/skills")].includes(s)||!/^[a-f\d]{64}$/u.test(o.entry.contentHash)||!/^[a-z][a-z\d]*(?:[.-][a-z\d]+)*$/u.test(Un.basename(o.entry.root)))&&Q("宿主入口安装记录无效;保留文件并核对原安装")}return o}async function AN(e,t){let r=X$(e.projectRoot,e.scope,e.userRoot),n=await k3(r,t);if(!n)return null;let i=`${n.packageRef}/application.json`;return await tD(r,i,"file"),ka(await ya(Un.join(r,n.packageRef)))!==n.contentHash&&Q("已安装版本内容发生漂移;恢复原包后继续"),Un.join(r,i)}var rD=x(()=>{"use strict";lt();Z$();kl()});var nD=x(()=>{"use strict";$g()});import Kt from"node:path";function No(e,t){let r=Kt.relative(e,t);return!r||!Kt.isAbsolute(r)&&r!==".."&&!r.startsWith(".."+Kt.sep)}function b3(e,t,r){if(!t.workspaceFrom)return e.projectRoot;let n=r?.input;for(let i of t.workspaceFrom.split("."))n=n&&typeof n=="object"?n[i]:void 0;if(typeof n!="string"||!Kt.isAbsolute(n))throw new Error("当前 Action 缺少已声明的实际写入工作区");return n}function iD(e){let t=Kt.resolve(e.projectRoot),r=[".git","node_modules",".claude",".agents",".codex",".cursor",".comet/runtime",".comet/applications",".comet/creator"].map(s=>Kt.resolve(t,s)),n={manifest:e.manifest,skills:e.skills,projectRoot:t},i=["AGENTS.md","AGENTS.override.md","CLAUDE.md"].map(s=>Kt.join(t,s)),o=e.manifest.bindings.filter(s=>s.usage==="action"&&e.skills.get(s.skillId)?.adapter.sideEffect==="write"),a=e.manifest.bindings.some(s=>s.usage==="action");return async(s,c)=>{if(c.intent!=="write")return{allowed:!0,reason:"此请求没有可归属的 SDK 应用写入"};try{if(!c.targets.length)throw new Error("SDK 应用写入必须声明实际文件");let l=[];for(let R of c.targets){let N=Kt.resolve(t,R),b=Kt.relative(t,N);if(!b||!No(t,N))throw new Error("写入目标必须位于当前项目内");if(await ie(t,b.replaceAll("\\","/"),{expected:"file",label:"SDK 应用写入"}),No(Kt.resolve(e.packageRoot),N)||r.some(E=>No(E,N))||i.some(E=>!Kt.relative(E,N))||!Kt.relative(Kt.join(t,".comet/current-change.json"),N))throw new Error("固定应用、SDK 状态与宿主配置只能由正式 Runtime 或安装入口维护");l.push(N)}let u=Kt.join(t,".comet/requests");if(l.every(R=>No(u,R)&&R.endsWith(".json")))return{allowed:!0,reason:"临时协议请求不是推进状态;Runtime 仍核对身份与批准"};let f=[],d=new Set,p=0,m=async R=>{if(d.has(R.runId))throw new Error("子流程归属循环");if((["running","waiting"].includes(R.status)||R.actions.some(b=>b.status==="pending"||Qn(b))||R.ready.length>0||R.waits.some(b=>b.status==="pending")||(R.evidenceWaits??[]).some(b=>b.status==="pending"))&&++p>128)throw new Error("活跃子流程超出安全读取范围");d.add(R.runId),f.push(R);for(let b of R.children){let E=R.actions.find(W=>W.id===b.actionId);if(!E||E.type!=="child_workflow")throw new Error("子流程与 SDK Action 归属不一致");if(!E.claim)continue;let I=await e.readChild(b.runId);if(I.runId!==b.runId||I.workflow.id!==b.workflow.id||I.workflow.version!==b.workflow.version||I.lineage.length!==R.lineage.length+1||I.lineage.at(-1)!==R.runId||R.lineage.some((W,F)=>I.lineage[F]!==W))throw new Error("子流程没有当前 SDK Run 的有效归属");await m(I)}};await m(s);let h=["completed","cancelled","failed"].includes(s.status),g=[],v=[];for(let R of f)for(let N of o.filter(b=>b.workflowId===R.workflow.id)){let b=e.skills.get(N.skillId),E=R.actions.filter(I=>I.stepId===N.stepId);for(let I of E){let W=b3(e,N,I);v.push(...b.adapter.scope.map(F=>Kt.resolve(W,F))),!(h||["cancelled","failed"].includes(R.status)||I.status!=="running")&&(Al(n,I,R),bl(n,R,I,f),g.push(...b.adapter.scope.map(F=>Kt.resolve(W,F))))}!N.workspaceFrom&&!E.length&&v.push(...b.adapter.scope.map(I=>Kt.resolve(t,I)))}let w=Kt.join(t,".comet/evidence",e.manifest.id),y=!h&&f.some(R=>R.actions.some(N=>["running","unknown"].includes(N.status)));for(let R of l)if(!(No(u,R)&&R.endsWith(".json"))&&!(y&&No(w,R))){if(h){if(v.some(N=>No(N,R))||No(Kt.join(t,".comet"),R))throw new Error("已结束 Run 的声明产物保持固定;继续修改应启动新的 Run")}else if((!e.custom||a)&&!g.some(N=>No(N,R)))throw new Error("当前 SDK Action 没有此写入权限;先确认当前提案并领取允许写入的 Action")}return e.custom?await e.custom(s,c):{allowed:!0,reason:h?"目标不属于已结束应用或控制资源":"写入属于当前已批准且已领取的 SDK Action"}}catch(l){return{allowed:!1,reason:l instanceof Error?l.message:"无法安全核对 SDK 应用写入"}}}}var oD=x(()=>{"use strict";lt();$g()});function bf(e,t,r){return(!e||typeof e!="object"||Array.isArray(e))&&Q(`${r} 必须是 JSON 对象`),Object.keys(e).some(n=>!t.includes(n))&&Q(`${r} 含未声明字段`),e}function hi(e,t,r=256){(typeof e!="string"||!e.trim()||e.length>r)&&Q(`${t} 必须是长度不超过 ${r} 的非空文本`)}function N3(e,t){let r=bf(e,["title","description","steps"],"应用展示信息");if(r.title!==void 0&&hi(r.title,"应用展示名称"),r.description!==void 0&&hi(r.description,"应用展示说明",4e3),r.steps===void 0)return;(!Array.isArray(r.steps)||r.steps.length>aD)&&Q("步骤展示信息必须是有界数组");let n=new Set;for(let i of r.steps){let o=bf(i,["workflowId","stepId","title","phase","description","outputFields"],"步骤展示信息");hi(o.workflowId,"展示流程 ID"),hi(o.stepId,"展示步骤 ID"),hi(o.title,"步骤展示名称"),o.phase!==void 0&&hi(o.phase,"步骤阶段名称"),o.description!==void 0&&hi(o.description,"步骤展示说明",4e3);let a=JSON.stringify([o.workflowId,o.stepId]);if(n.has(a)&&Q(`重复步骤展示信息:${o.workflowId}/${o.stepId}`),n.add(a),t){let c=t.filter(l=>l.id===o.workflowId);(!c.length||c.some(l=>!Object.hasOwn(l.steps,o.stepId)))&&Q(`展示信息引用不存在的步骤:${o.workflowId}/${o.stepId}`)}if(o.outputFields===void 0)continue;(!Array.isArray(o.outputFields)||o.outputFields.length>32)&&Q("步骤展示输出字段必须是有界数组");let s=new Set;for(let c of o.outputFields){let l=bf(c,["path","label"],"步骤展示输出字段");hi(l.path,"展示输出路径",512),hi(l.label,"展示输出名称"),(!/^[A-Za-z_][A-Za-z_0-9]*(?:\.(?:[A-Za-z_][A-Za-z_0-9]*|0|[1-9][0-9]*))*$/u.test(l.path)||l.path.split(".").some(u=>["__proto__","constructor","prototype"].includes(u)))&&Q(`展示输出字段路径无效:${l.path}`),s.has(l.path)&&Q(`重复展示输出字段:${l.path}`),s.add(l.path)}}}function RN(e){(typeof e!="string"||e.length>1024||!/^[A-Za-z0-9_-]+(?:\/[A-Za-z0-9_-]+)*\.json$/u.test(e)||["application.json","installation.json"].includes(e))&&Q("应用流程定义必须声明固定包内的 JSON 相对路径")}function S3(e,t){let r=typeof e=="string"?e:Ei(e),n=bf(JSON.parse(r),["schema","application","workflows","presentation"],"应用流程定义");n.schema!=="comet.workflow.application.definition.v1"&&Q("应用流程定义格式不受支持");let i=bf(n.application,["id","version"],"流程定义应用身份");hi(i.id,"流程定义应用 ID"),hi(i.version,"流程定义应用版本"),t&&(t.id!==i.id||t.version!==i.version)&&Q("流程定义与应用固定身份不匹配"),(!Array.isArray(n.workflows)||!n.workflows.length||n.workflows.length>A3)&&Q("应用流程定义必须包含有界的完整流程数组");let o=0,a=0,s=n.workflows.map(l=>((!l||typeof l!="object"||!l.steps||typeof l.steps!="object")&&Q("应用流程定义缺少步骤"),o+=Object.keys(l.steps).length,a+=Array.isArray(l.transitions)?l.transitions.length:0,(o>aD||a>R3)&&Q("应用流程定义超过步骤或转移数量限制"),Bn(l))),c=new Set;for(let l of s){let u=JSON.stringify([l.id,l.version]);c.has(u)&&Q(`重复流程身份:${l.id}@${l.version}`),c.add(u)}for(let l of s)for(let[u,f]of Object.entries(l.steps))f.type==="child_workflow"&&!c.has(JSON.stringify([f.workflow.id,f.workflow.version]))&&Q(`子流程定义不存在:${l.id}/${u}`);return n.presentation!==void 0&&N3(n.presentation,s),{schema:"comet.workflow.application.definition.v1",application:{id:i.id,version:i.version},workflows:s,...n.presentation===void 0?{}:{presentation:n.presentation}}}function sD(e,t){if(t.definition!==void 0)return RN(t.definition),Object.hasOwn(e,t.definition)||Q("固定包缺少声明的应用流程定义"),S3(Buffer.from(e[t.definition],"base64").toString("utf8"),t)}function cD(e,t){let r=n=>n.map(i=>{let o=Bn(i);return[o.id,o.version,D(o)]}).sort((i,o)=>JSON.stringify(i).localeCompare(JSON.stringify(o),"en"));D(r(e.workflows))!==D(r(t))&&Q("实际工厂的流程与固定流程定义不匹配,请同步确认方案")}function NN(e,t){let r=new Map(e.workflows.map(i=>[JSON.stringify([i.id,i.version]),D(i)])),n=JSON.stringify([t.workflow.id,t.workflow.version]);return r.get(n)===t.workflow.hash&&t.definitionHashes[n]===t.workflow.hash&&Object.entries(t.definitionHashes).every(([i,o])=>r.get(i)===o)}var A3,aD,R3,lD=x(()=>{"use strict";ze();xr();kl();A3=256,aD=4096,R3=16384});import{createHash as E3}from"node:crypto";async function dD(e,t){let r={},n={},i=new uD.Ajv({strict:!0,allErrors:!0});for(let o of t){let a=await Qe(e,o.ref,16777216,{label:`必需产物 ${o.ref}`}),s=a.bytes.toString("utf8");if(o.nonEmpty&&!s.trim())throw new Error(`必需产物不能为空:${o.ref}`);if(o.requiredText?.some(c=>!s.includes(c)))throw new Error(`实际工件不满足内容要求:${o.ref}`);if(o.requiredHeadings?.length){let c=new Set,l,u="";for(let d of s.split(/\r?\n/u)){let p=/^ {0,3}(`{3,}|~{3,})/u.exec(d);if(p){let h=p[1];l?l.char===h[0]&&h.length>=l.length&&d.slice(p[0].length).trim()===""&&(l=void 0):l={char:h[0],length:h.length},u="";continue}if(l)continue;let m=/^ {0,3}#{1,6}\s+(.+?)(?:\s+#+)?\s*$/u.exec(d);m?c.add(m[1].trim()):u.trim()&&/^ {0,3}(?:=+|-+)\s*$/u.test(d)&&c.add(u.trim()),u=/^ {0,3}\S/u.test(d)?d:""}let f=o.requiredHeadings.filter(d=>!c.has(d));if(f.length)throw new Error(`必需产物缺少章节:${o.ref},${f.join("、")}`)}if(o.schema!==void 0){let c=o.schema;if(typeof c!="boolean"&&(c===null||Array.isArray(c)||typeof c!="object"||c.$async===!0))throw new Error(`工件需要同步 JSON Schema:${o.ref}`);let l=i.compile(c);if(!l(JSON.parse(s)))throw new Error(`实际工件结构无效:${o.ref},${i.errorsText(l.errors)}`)}r[o.ref]=s,n[o.ref]=E3("sha256").update(a.bytes).digest("hex")}return{files:r,artifactHashes:n}}var uD,fD=x(()=>{"use strict";uD=dr(bh(),1);ze();lt();kl()});import mD from"node:path";function SN(e,t,r,n){let i=t.bindings.find(a=>a.usage==="action"&&a.workflowId===r.workflow.id&&a.stepId===n.stepId);if(!i?.workspaceFrom)return e;let o=EN(n.input,i.workspaceFrom);if(typeof o!="string"||!mD.isAbsolute(o))throw new Error("产物检查缺少当前 Action 已声明的实际工作区");return o}function hD(e){(typeof e!="string"||!e||e.length>4096||e.includes("\\")||e.includes(":")||e.includes("\0")||mD.posix.isAbsolute(e)||e.split("/").some(r=>!r||r==="."||r===".."||/[ .]$/u.test(r)))&&Q("产物引用必须是项目内安全相对路径"),([".git","node_modules",".agents",".claude",".codex",".cursor",".comet/runtime",".comet/applications",".comet/creator"].some(r=>e.toLowerCase()===r||e.toLowerCase().startsWith(r+"/"))||["agents.md","agents.override.md","claude.md",".comet/current-change.json"].includes(e.toLowerCase()))&&Q(`产物引用不能指向控制资源:${e}`)}function pD(e){(typeof e!="string"||!/^[A-Za-z_][A-Za-z_0-9]*(?:\.[A-Za-z_][A-Za-z_0-9]*)*$/u.test(e)||e.split(".").some(t=>["__proto__","constructor","prototype"].includes(t)))&&Q("产物字段选择器无效")}function CN(e){(!Array.isArray(e)||e.length>256)&&Q("阶段产物契约必须是有界数组");let t=new Set;for(let r of e){(!r||typeof r!="object"||Array.isArray(r)||Object.keys(r).some(o=>!["workflowId","stepId","artifacts","noArtifactsReason","replaces"].includes(o)))&&Q("阶段产物契约含未声明字段");let n=r;(typeof n.workflowId!="string"||!n.workflowId.trim()||typeof n.stepId!="string"||!n.stepId.trim()||t.has(Bg(n.workflowId,n.stepId))||!Array.isArray(n.artifacts)||n.artifacts.length>64)&&Q("阶段产物契约缺少唯一流程、步骤或产物列表"),t.add(Bg(n.workflowId,n.stepId)),!n.artifacts.length&&(typeof n.noArtifactsReason!="string"||!n.noArtifactsReason.trim())&&Q(`无强制产物的阶段需要说明原因:${Bg(n.workflowId,n.stepId)}`),n.artifacts.length&&n.noArtifactsReason!==void 0&&Q("必需产物与无产物声明不能同时存在"),n.replaces&&(!Array.isArray(n.replaces)||n.replaces.some(o=>typeof o!="string"||!o.trim())||new Set(n.replaces).size!==n.replaces.length)&&Q("替代产物的步骤声明无效");let i=new Set;for(let o of n.artifacts){(!o||typeof o!="object"||Object.keys(o).some(s=>!["ref","refFrom","sha256From","nonEmpty","schema","requiredText","requiredHeadings"].includes(s))||!!o.ref==!!o.refFrom)&&Q("必需产物需要唯一的 ref 或 refFrom"),o.ref!==void 0&&hD(o.ref),o.refFrom!==void 0&&pD(o.refFrom),o.sha256From!==void 0&&pD(o.sha256From);let a=o.ref??`output:${o.refFrom}`;i.has(a)&&Q("阶段产物引用重复"),i.add(a),o.nonEmpty!==void 0&&typeof o.nonEmpty!="boolean"&&Q("nonEmpty 必须是布尔值");for(let s of[o.requiredText,o.requiredHeadings])s!==void 0&&(!Array.isArray(s)||!s.length||s.length>64||s.some(c=>typeof c!="string"||!c.trim()))&&Q("产物内容检查必须是非空文本数组")}}}function C3(e,t){for(let r of t){let n=e.workflows.find(i=>i.id===r.workflowId);n?.steps[r.stepId]||Q(`阶段产物契约引用不存在的步骤:${Bg(r.workflowId,r.stepId)}`);for(let i of r.replaces??[])n.steps[i]||Q(`替代产物的步骤不存在:${i}`);r.artifacts.length&&!["handoff","invoke_skill","call_tool","child_workflow"].includes(n.steps[r.stepId].type)&&Q("必需产物必须绑定可回传结果的执行步骤"),n.steps[r.stepId].type==="child_workflow"&&r.artifacts.some(i=>!i.sha256From)&&Q("子流程产物需要 sha256From,读取子流程结果中的实际摘要")}}async function gD(e,t,r){let n=t.artifacts.map(o=>{let a=o.ref??EN(r,o.refFrom);return hD(a),{...o,ref:a,nonEmpty:o.nonEmpty!==!1}}),i=await dD(e,n);return{...i,artifacts:n.map(({ref:o})=>({uri:o,sha256:i.artifactHashes[o]}))}}async function vD(e,t,r){if(r.status!=="succeeded"||!t.artifacts.length)return;let n=await gD(e,t,r.output);for(let i=0;i<n.artifacts.length;i++){let o=n.artifacts[i],a=t.artifacts[i];if((a.sha256From?EN(r.output,a.sha256From):r.artifacts?.find(c=>c.uri===o.uri)?.sha256)!==o.sha256)throw new Error(`必需产物缺少当前结果的实际摘要或内容已变化:${o.uri}`)}}async function Af(e,t,r,n,i,o){let a=t.filter(c=>c.workflowId===r.workflow.id),s=new Set(a.find(c=>c.stepId===n)?.replaces??[]);for(let c of a)if(i[c.stepId])for(let l of c.replaces??[])i[c.stepId].sequence>(i[l]?.sequence??-1)&&s.add(l);for(let c of a){let l=i[c.stepId];if(!l||!c.artifacts.length||s.has(c.stepId))continue;let u=r.actions.find(f=>f.stepId===c.stepId&&["succeeded","failed"].includes(f.status)&&r.actionContexts[f.id]?.sequence===l.sequence);if(!u?.outcome||D(u.outcome.output)!==D(l.value))throw new Error(`依赖产物没有对应的原 Action 证据:${c.stepId}`);await vD(o?SN(e,o,r,u):e,c,u.outcome)}}function wD(e,t){let r=t.manifest.artifactContracts;if(r===void 0)return e;CN(r),C3(e,r);let n=(o,a)=>r.find(s=>s.workflowId===o.workflow.id&&s.stepId===a),i=async o=>{o.outcome.status==="succeeded"&&await Af(t.projectRoot,r,o.run,o.action.stepId,o.run.actionContexts[o.action.id]?.results??{},t.manifest);let a=n(o.run,o.action.stepId);a&&await vD(SN(t.projectRoot,t.manifest,o.run,o.action),a,o.outcome)};return{...e,executors:e.executors?.map(o=>({...o,...o.preflight?{async preflight(a,s,c){c&&await Af(t.projectRoot,r,c,a.stepId,c.actionContexts[a.id]?.results??{},t.manifest),await o.preflight?.(a,s,c)}}:{},async execute(a,s,c){let l=await o.execute(a,s,c),u=c?n(c,a.stepId):void 0;if(!u?.artifacts.length||l.status!=="succeeded")return l;try{let f=await gD(SN(t.projectRoot,t.manifest,c,a),u,l.output);return{...l,artifacts:[...(l.artifacts??[]).filter(d=>!f.artifacts.some(p=>p.uri===d.uri)),...f.artifacts]}}catch{return l}}})),validators:e.validators?.map(o=>({...o,async validate(a){let s=await o.validate(a);if(!s.accepted)return s;try{return await i(a),s}catch(c){return{accepted:!1,reason:c instanceof Error?c.message:String(c)}}}})),async validateOutcome(o){try{await i(o);let a=await e.validateOutcome?.(o)??{accepted:!0};return a.accepted&&await i(o),a}catch(a){return{accepted:!1,reason:a instanceof Error?a.message:String(a)}}}}}var EN,Bg,yD=x(()=>{"use strict";ze();fD();kl();EN=(e,t)=>t.split(".").reduce((r,n)=>r&&typeof r=="object"&&Object.hasOwn(r,n)?r[n]:void 0,e),Bg=(e,t)=>`${e}/${t}`});import{promises as _N}from"node:fs";import Ar from"node:path";import{createRequire as _3,isBuiltin as I3}from"node:module";function SD(e){return["completed","cancelled"].includes(e.status)&&!e.actions.some(t=>t.status==="pending"||Qn(t))&&e.children.length===0&&!e.ready.length&&!e.waits.some(t=>t.status==="pending")&&!(e.evidenceWaits??[]).some(t=>t.status==="pending")}function Ds(e){return(typeof e!="string"||!/^[a-z][a-z\d]*(?:[.-][a-z\d]+)*$/u.test(e))&&Q("应用身份必须是小写名称"),e}async function IN(e,t,r=!1,n=!1){let i=Le(e),o=()=>{if(Le(e)!==i)throw new A("WORKFLOW_CHANGED","工作区身份已改变,请重新加载应用 Runtime")},a=async()=>{if(o(),!r){if(await Cn(e)!==i)throw new A("WORKFLOW_CHANGED","工作区身份已改变,请重新加载应用 Runtime");o()}},s=ht({rootDir:Ar.join(i,"applications",Ds(t)),mirroredRevisionPaths:["run.revision"],writerProtocol:"application-holder-v1",...n?{singleWriter:!0}:{}}),c=(u,f,d)=>{let p=s.prepareCompareAndSwap(u,f,d);return async()=>{if(o(),r)throw new A("READ_ONLY_OPERATION","应用诊断不能推进 Run");await a();let m=await s.settleRun(u);if(["closing","closed","reopening"].includes(m)){let g=await s.read(u);if(!g||g.revision!==f)return!1;m==="closing"&&await s.closeRun(u,g.revision),await s.reopenRun(u,g.revision)}let h=await p();return h&&d.application.base==="standalone"&&SD(d.run)&&await s.closeRun(u,d.revision),h}},l=async(u,f)=>(await a(),await s[f?"readProjection":"read"](u));return{queryScope:s.queryScope,read:u=>l(u,!1),readProjection:u=>l(u,!0),compareAndSwap:async(u,f,d)=>c(u,f,d)(),prepareCompareAndSwap:c,restoreCheckpoint:async(u,f,d)=>{if(o(),r)throw new A("READ_ONLY_OPERATION","应用诊断不能恢复 Run");if(await a(),await s.settleRun(u)==="closed"){let m=await s.read(u);if(!m||m.revision!==f)return!1;await s.reopenRun(u,m.revision)}return s.restoreCheckpoint(u,f,d)}}}async function ED(e,t,r){return ht({rootDir:Ar.join(Le(e),"applications",Ds(t)),mirroredRevisionPaths:["run.revision"]}).readPartitionMetadata(r)}async function bD(e){let t=await ya(e.application.packageRoot),r=PN(JSON.parse(Buffer.from(t["application.json"],"base64").toString("utf8")));if(r.id!==e.application.id||r.version!==e.application.version||r.base!==e.application.base||D({package:ka(t),skills:r.skills.map(n=>({id:n.id,contentHash:n.contentHash}))})!==e.application.contentHash)throw new A("SCOPE_HELD",`固定占用应用定义无法验证:${e.application.id} / ${e.runId}`);return r}function AD(e,t,r){return e.actions.filter(n=>n.type==="invoke_skill"&&Qn(n)&&t.bindings.some(i=>{let o=t.skills.find(a=>a.id===i.skillId);return i.workflowId===e.workflow.id&&i.stepId===n.stepId&&i.usage==="action"&&o&&o.adapter.sideEffect!=="read"&&o.adapter.scope.length>0})).map(n=>({runId:e.runId,applicationContentHash:r,actionId:n.id,attempt:n.attempt,inputHash:n.inputHash,claimToken:n.claim?_h(n.claim.token):null}))}async function CD(e){let t=Tn(e.run,e.runId),r=t.actions.filter(n=>n.type==="invoke_skill"&&Qn(n));if(!r.length)return!1;try{let n=await ya(e.application.packageRoot),i=PN(JSON.parse(Buffer.from(n["application.json"],"base64").toString("utf8")));return D({package:ka(n),skills:i.skills.map(o=>({id:o.id,contentHash:o.contentHash}))})!==e.application.contentHash?!0:r.some(o=>i.bindings.some(a=>{let s=i.skills.find(c=>c.id===a.skillId);return a.workflowId===t.workflow.id&&a.stepId===o.stepId&&a.usage==="action"&&s&&s.adapter.sideEffect!=="read"&&s.adapter.scope.length>0}))}catch{return!0}}function RD(e,t,r=!1){let n=Ar.join(Le(e),"applications",Ds(t)),i=ht({rootDir:n,mirroredRevisionPaths:["run.revision"],writerProtocol:"application-holder-v1",...r?{singleWriter:!0}:{}});return bN({rootDir:n,read:o=>i.read(o),settle:o=>i.settleRun(o),holds:CD})}async function xN(e,t,r){return(await x3(e,t,r))?.run??null}async function x3(e,t,r){let n=await(await IN(e,t,!0)).read(r);if(!n)return null;if(n.application.id!==t||n.runId!==n.run.runId||n.revision!==n.run.revision)throw new A("INVALID_RUN","应用归属与 SDK Run 不一致");return n.run=Tn(n.run,r),n}function PN(e){(!e||typeof e!="object"||Array.isArray(e))&&Q("应用文件必须是 JSON 对象");let t=e;return t.artifactContracts!==void 0&&CN(t.artifactContracts),t.schema!=="comet.workflow.application.v1"&&Q("应用格式不受支持,请重新生成 SDK 应用;原文件会保留"),t.definition!==void 0&&RN(t.definition),t.rule!==void 0&&(typeof t.rule!="string"||!t.rule.endsWith(".md")||Ar.isAbsolute(t.rule)||t.rule.includes("\\")||t.rule.includes(":")||t.rule.split("/").some(r=>!r||r==="."||r===".."))&&Q("应用规则 Rule 必须声明固定包内的 Markdown 相对路径"),Ds(t.id),eN.includes(t.id)&&Q(`应用身份 ${t.id} 与内置应用冲突,请使用独立名称`),(!t.version?.trim()||!["standalone","native","classic-full","classic-hotfix","classic-tweak"].includes(t.base)||!t.runtimeVersion?.trim()||!t.entrySkill?.trim()||!t.module?.endsWith(".mjs")||!Array.isArray(t.skills)||!Array.isArray(t.bindings))&&Q("应用定义缺少版本、基础流程、入口或绑定"),t}async function TN(e,t,r){let n=await(await IN(await _N.realpath(e),t,!0)).readProjection(r);return n?Ar.join(n.application.packageRoot,"application.json"):await AN({projectRoot:e,scope:"project"},Ds(t))??await AN({projectRoot:e,scope:"user"},Ds(t))??Ar.join(e,".comet/applications",Ds(t),"application.json")}async function Wg(e){let t=await _N.realpath(e.projectRoot),r=Ar.resolve(e.file);Ar.basename(r)!=="application.json"&&Q("应用入口文件必须命名为 application.json");let n=await _N.realpath(Ar.dirname(r));n===t&&Q("应用包须放在独立目录,不能包含项目的运行状态");let i=await ya(n),o=PN(JSON.parse(Buffer.from(i["application.json"]??"","base64").toString("utf8"))),a=sD(i,o);o.rule&&(!o.rule.endsWith(".md")||!i[o.rule]||!Buffer.from(i[o.rule],"base64").toString("utf8").trim())&&Q("应用规则 Rule 必须是固定包内的非空 Markdown 文件");let s=M$(),c=o.runtimeVersion==="0.5.2"&&s==="0.5.3"&&!!e.runId&&(o.base==="native"||o.base.startsWith("classic-"));o.runtimeVersion!==s&&!c&&Q(`应用要求 Runtime ${o.runtimeVersion},当前是 ${s}`),(!i[o.entrySkill]||!i[o.module])&&Q("应用入口 Skill 或执行模块缺失");let l=new Map;for(let S of o.skills)l.has(S.id)&&Q(`重复 Skill 身份:${S.id}`),l.set(S.id,await wN(S,n));let u={id:o.id,version:o.version,base:o.base,runtimeVersion:o.runtimeVersion,projectRoot:t,packageRoot:n,contentHash:D({package:ka(i),skills:[...l.values()].map(S=>({id:S.id,contentHash:S.contentHash}))})},f=async()=>{let S=await ya(n),P=await Promise.all(o.skills.map(V=>wN(V,n)));if(D({package:ka(S),skills:P.map(V=>({id:V.id,contentHash:V.contentHash}))})!==u.contentHash)throw new A("WORKFLOW_CHANGED","运行中的应用或依赖发生漂移;恢复原内容后继续原 Action")};if(e.expectedIdentity&&D(u)!==D(e.expectedIdentity))throw new A("WORKFLOW_CHANGED","恢复需要原固定应用包、依赖和工作区");let d=o.base!=="standalone",p=await IN(t,o.id,e.readOnly,d),m=S=>{if(D(S.application)!==D(u))throw new A("WORKFLOW_CHANGED","应用定义、执行/验证绑定、Skill 或工作区归属发生变化;请恢复原应用包和依赖后继续原 Run");if(S.revision!==S.run.revision||S.runId!==S.run.runId)throw new A("INVALID_RUN","应用归属与 SDK Run 不一致")},h;if(e.runId){let S=await p.readProjection(e.runId);S&&(m(S),h=(await Ya({...p,readProjection:async()=>S},e.runId)).run)}await hN;for(let[S,P]of Object.entries(i)){if(!S.endsWith(".mjs"))continue;let B=Buffer.from(P,"base64").toString("utf8");for(let V of mN(B)[0]){if(V.d===-2)continue;let H=V.n;if(H||Q(`应用模块不能动态选择未固定的导入:${S}`),I3(H)||H==="@rpamis/comet/runtime"||H==="@rpamis/comet/applications"||H==="@rpamis/comet/applications/compiler"||H==="@rpamis/comet/applications/native"||H==="@rpamis/comet/applications/classic")continue;H.startsWith(".")||Q(`应用模块依赖未固定:${S} -> ${H},请 bundle 后再加载`);let U=Ar.posix.normalize(Ar.posix.join(Ar.posix.dirname(S),H));(!i[U]||U.startsWith("../"))&&Q(`应用模块依赖缺失或越过包目录:${S} -> ${H}`),!U.endsWith(".mjs")&&!U.endsWith(".json")&&Q(`执行依赖必须是可检查的 .mjs 或 JSON:${S} -> ${H},请先 bundle`)}}let g=kD.get(n);g&&g!==u.contentHash&&Q("当前进程已加载不同的应用实现,请在新进程加载新版本"),kD.set(n,u.contentHash);let v=_3(r)(Ar.join(n,o.module));typeof v.createApplication!="function"&&Q("应用模块必须导出 createApplication");let w={manifest:structuredClone(o),skills:l,projectRoot:t,packageRoot:n,identity:u,createSkillExecutor:S=>K$({manifest:o,skills:l,projectRoot:t},S)};if(h&&!e.useLatestDefinition){let S;Object.defineProperty(w,"existingRun",{enumerable:!0,get:()=>S??=Pr(h)})}let y=await v.createApplication(w);(!y||!Array.isArray(y.workflows)||!y.workflows.length)&&Q("应用模块必须提供完整 SDK 工作流"),y=wD(y,{manifest:o,projectRoot:t});let R=y.workflows.map(Bn);a&&(c?h&&!NN(a,h)&&!NN({...a,workflows:R},h)&&Q("旧固定应用 Run 不匹配原定义或当前业务定义"):cD(a,R));let N=new Set;for(let S of o.bindings){let P=`${S.workflowId}/${S.stepId}/${S.usage}${S.usage==="guidance"?`/${S.skillId}`:""}`;S.workspaceFrom!==void 0&&!/^[a-zA-Z][\w]*(?:\.[a-zA-Z][\w]*)*$/u.test(S.workspaceFrom)&&Q(`工作区输入路径无效:${P}`),N.has(P)&&Q(`重复 Skill 绑定:${P}`),N.add(P);let B=R.find(U=>U.id===S.workflowId),V=B?.steps[S.stepId],H=l.get(S.skillId);if((!V||!H)&&Q(`绑定的工作或 Skill 不存在:${P}`),(!S.capability?.trim()||!H.adapter.review.capabilities.some(U=>U.id===S.capability))&&Q(`真实 Skill 没有已审查的所需能力:${P}`),S.usage==="guidance"){H.adapter.kind!=="guidance"&&Q("只有只读指导 Skill 可附加为 guidance");continue}if(S.usage==="subworkflow"){(H.adapter.kind!=="subworkflow"||V.type!=="child_workflow")&&Q("完整流程必须绑定显式 child_workflow");continue}if((S.usage!=="action"||!["action","check"].includes(H.adapter.kind)||V.type!=="invoke_skill"||V.ref!==S.skillId)&&Q(`Skill 工作类型或引用不匹配:${P}`),H.adapter.controlsApproval&&Q("接管审批的 Skill 必须适配为隔离的子流程"),(V.outputSchema===void 0||D(V.outputSchema)!==D(H.adapter.outputSchema))&&Q(`Skill 输出与工作流契约不匹配:${P}`),H.adapter.completion!=="self-report"&&!(H.adapter.completion==="machine-check"&&o.artifactContracts?.some(U=>U.workflowId===S.workflowId&&U.stepId===S.stepId&&U.artifacts.length))&&(!V.validator||!y.validators?.some(U=>U.id===V.validator?.id&&U.version===V.validator.version))&&Q(`机器检查或独立评审需要真实验证器:${P}`),H.adapter.requiredCapabilities.some(U=>!V.requiredCapabilities?.includes(U))&&Q(`Skill 必需宿主能力未传到 Action:${P}`),H.adapter.sideEffect!=="read"){let U=S.authorizationFrom?B.steps[S.authorizationFrom]:void 0,se=S.authorizationChoices??["approved"];(U?.type!=="ask_user"||!Array.isArray(se)||!se.length||se.some(ee=>typeof ee!="string"||!U.choices.includes(ee)))&&Q(`有副作用的 Skill 缺少有效父流程审批:${P}`)}H.adapter.sideEffect==="external"&&V.retry!=="reconcile"&&Q(`外部 Skill 必须先核对再重试:${P}`)}for(let S of R){let P=(H,U,se)=>{H&&!U?.some(ee=>ee.id===H.id&&ee.version===H.version)&&Q(`${se} 未注册固定实现:${H.id}@${H.version}`)};P(S.transitionHandler,y.transitionHandlers,"转移处理器"),P(S.stateValidator,y.stateValidators,"状态验证器");for(let H of Object.values(S.commands??{}))P(H.validator,y.commandValidators,"命令验证器");for(let[H,U]of Object.entries(S.steps))U.type==="await_evidence"?P(U.validator,y.evidenceValidators,"证据验证器"):P(U.validator,y.validators,"工作验证器"),U.type==="invoke_skill"&&!o.bindings.some(se=>se.workflowId===S.id&&se.stepId===H&&se.usage==="action")&&Q(`Skill Action 缺少适配绑定:${S.id}/${H}`);let B=o.bindings.filter(H=>H.workflowId===S.id&&H.usage==="action"&&l.get(H.skillId).adapter.sideEffect!=="read"),V=(H,U,se=new Set)=>H===U?!0:se.has(H)?!1:(se.add(H),S.transitions.some(ee=>ee.from===H&&V(ee.to,U,se)));for(let H=0;H<B.length;H++)for(let U of B.slice(H+1)){let se=B[H];l.get(se.skillId).adapter.sideEffect==="write"&&l.get(U.skillId).adapter.sideEffect==="write"&&!!se.workspaceFrom!=!!U.workspaceFrom&&!V(se.stepId,U.stepId)&&!V(U.stepId,se.stepId)&&Q(`并行写入不能混用声明工作区和默认范围:${se.stepId} / ${U.stepId}`),!se.workspaceFrom&&!U.workspaceFrom&&l.get(se.skillId).adapter.scope.some(ee=>l.get(U.skillId).adapter.scope.some(fe=>l.get(se.skillId).adapter.sideEffect==="write"&&l.get(U.skillId).adapter.sideEffect==="write"?Og(Ar.resolve(t,ee),Ar.resolve(t,fe)):fe===ee))&&!V(se.stepId,U.stepId)&&!V(U.stepId,se.stepId)&&Q(`并行 Skill 的写入范围冲突:${se.stepId} / ${U.stepId},请声明隔离或执行顺序`)}}let b=()=>{if(e.readOnly)throw new A("READ_ONLY_OPERATION","应用诊断不能恢复或推进 Run")},E=Le(t),I=async S=>{if(Le(t)!==E)throw new A("WORKFLOW_CHANGED","工作区身份已改变,请重新加载应用 Runtime");return await Cn(t),S()},W=Ar.join(E,"applications",o.id),F=ht({rootDir:W,mirroredRevisionPaths:["run.revision"],writerProtocol:"application-holder-v1",...d?{singleWriter:!0}:{}}),G=(S,P)=>P.type==="invoke_skill"&&o.bindings.some(B=>{let V=l.get(B.skillId);return B.workflowId===S.workflow.id&&B.stepId===P.stepId&&B.usage==="action"&&V&&V.adapter.sideEffect!=="read"&&V.adapter.scope.length>0}),Z=bN({rootDir:W,read:S=>F.read(S),settle:S=>F.settleRun(S),holds:S=>S.application.contentHash!==u.contentHash?CD(S):Tn(S.run,S.runId).actions.some(P=>Qn(P)&&G(S.run,P))}),Ae=S=>JSON.stringify(S?.actions.filter(P=>G(S,P)&&Qn(P)).map(P=>[P.id,P.status,P.claim?.token,P.inputHash]).sort()??[]),re=S=>AD(S,o,u.contentHash),nt=async S=>{let P=await RD(t,S,S===o.id&&d).holders(),B=[];for(let V of P){let H=V.application.id===u.id&&V.application.contentHash===u.contentHash?o:await bD(V);B.push(...AD(Tn(V.run,V.runId),H,V.application.contentHash))}return B},rr=(S=!1)=>D$(E,o.id,nt,S),q=async(S,P,B=!1)=>{if(!o.bindings.some(ee=>{if(ee.workflowId!==S.workflow.id||ee.stepId!==P.stepId||ee.usage!=="action")return!1;let fe=l.get(ee.skillId);return fe&&fe.adapter.sideEffect!=="read"&&fe.adapter.scope.length>0}))return[];let H=jg({manifest:o,projectRoot:t},S,P);for(let ee of await rr(B)){if(ee===o.id||B&&!await W$(E,ee))continue;let fe=await RD(t,ee).holders();for(let de of fe){let k=Tn(de.run,de.runId);if(de.application.id!==ee||de.application.projectRoot!==t)throw new A("SCOPE_HELD",`应用 ${ee} 的固定占用身份无法验证:${k.runId}`);let C=await bD(de);for(let j of k.actions.filter(Qn))if(jg({manifest:C,projectRoot:t},k,j).some(O=>H.some(J=>O.write&&J.write?Og(O.ref,J.ref):O.ref===J.ref))){let O=new A("SCOPE_HELD",`写入范围仍由应用 ${ee} 的 Run ${k.runId} / Action ${j.id} 占用;请停止原执行或提交真实结果`);throw Object.assign(O,{blockedRunIds:[k.runId],blockedApplicationIds:[ee]}),O}}}let U=await Z.holders(),se=[];for(let ee of U){if(ee.runId===S.runId)continue;let fe=Tn(ee.run,ee.runId);if(ee.application.contentHash!==u.contentHash)throw new A("SCOPE_HELD",`其他固定版本仍占用应用工作区:${fe.runId}`);se.push(fe)}return se},ne={queryScope:p.queryScope,async readProjection(S){await f();let P=await p.readProjection(S);return P?(m(P),P.run):null},async read(S){await f();let P=await p.read(S);return P?(m(P),P.run):null},async restoreCheckpoint(S,P,B){return B=structuredClone(B),b(),await f(),I(async()=>{await f();let H=await p.read(S);if(H&&m(H),B.runId!==S||B.actions.some(ee=>ee.status==="running"))throw new A("INVALID_RUN","应用恢复必须使用同一 Run 的 portable checkpoint,活跃领取须先转为 unknown");let U=o.base==="native"?"native":o.base.startsWith("classic-")?"classic":null;if(U){let ee=await Ao(t,U,S);if(!ee||ee.format!=="sdk"||ee.application!==u.id||ee.runId!==S)throw new A("INVALID_RUN","恢复 Run 前须验证相同的固定应用和 change 归属")}let se={runId:S,revision:B.revision,application:u,run:B};m(se),await B$(E,o.id,S,re(B)),await rr(!0);for(let ee of B.actions.filter(fe=>Qn(fe)&&fe.type==="invoke_skill"))bl({manifest:o,skills:l,projectRoot:t},B,ee,await q(B,ee,!0));await fN(E,o.id,re(B),!0);try{return await Z.begin(S,!H),await p.restoreCheckpoint(S,P,se)}finally{await Z.finish(),await pN(E,o.id,nt,!0)}})},async compareAndSwap(S,P,B){b(),await f(),B=structuredClone(B);let V=p.prepareCompareAndSwap(S,P,{runId:S,revision:B.revision,application:u,run:B}),H=await p.read(S),U=(await Z.inspect())?.state!=="ready"||!H||Ae(H.run)!==Ae(B)||SD(B),se=async()=>{await f();let ee=await p.read(S);if(ee&&m(ee),ee||await rr(),(ee?.revision??null)!==P)return!1;for(let fe of B.actions)if(fe.status==="running"&&!ee?.run.actions.some(de=>de.id===fe.id&&de.status==="running"&&de.claim?.token===fe.claim?.token)&&(bl({manifest:o,skills:l,projectRoot:t},B,fe,await q(B,fe)),o.artifactContracts&&await Af(t,o.artifactContracts,B,fe.stepId,B.actionContexts[fe.id]?.results??{},o),fe.type==="invoke_skill")){Al({manifest:o,skills:l},fe,B);let de=y.executors?.find(k=>k.id===fe.claim?.executorId);if(!de)throw new A("EXECUTOR_UNAVAILABLE","Skill 必须由应用已配置的执行端口领取");if(de.supports(yN(fe))!==!0||!de.preflight)throw new A("EXECUTOR_UNSUPPORTED","Skill 执行端口缺少对应的领取预检");if(fe.requiredCapabilities.some(k=>!de.capabilities.includes(k)))throw new A("CAPABILITY_REQUIRED","已配置执行端口缺少 Skill 所需能力")}if(o.artifactContracts)for(let fe of B.waits)fe.status==="resolved"&&fe.decision?.choice==="approved"&&ee?.run.waits.some(de=>de.id===fe.id&&de.status==="pending")&&await Af(t,o.artifactContracts,B,fe.stepId,fe.results,o);if((ee?.revision??null)!==P||!U&&Ae(ee?.run)!==Ae(B))return!1;if(U){let fe=new Set(ee?re(ee.run).map(D):[]),de=re(B).filter(k=>!fe.has(D(k)));de.length&&(await rr(),await fN(E,o.id,de))}try{return U&&await Z.begin(S,!ee),await V()}finally{U&&(await Z.finish(),await pN(E,o.id,nt))}};return U?I(se):se()}},he=y.wrapStore?y.wrapStore(ne,u,{readOnly:e.readOnly}):ne;if(e.runId&&!h&&!e.readOnly&&y.wrapStore){let P=await he.read(e.runId)?await p.read(e.runId):null;if(P)return m(P),Wg(e)}let Ot={...y,...o.base==="standalone"?{inspectHook:iD({projectRoot:t,packageRoot:n,manifest:o,skills:l,custom:y.inspectHook,readChild:async S=>(await wr({...y,store:he}).inspectProjection(S)).run})}:{},async validateOutcome(S){if(S.action.type==="invoke_skill")try{Al({manifest:o,skills:l},S.action,S.run)}catch(P){return{accepted:!1,reason:P instanceof Error?P.message:"Skill 结果不满足应用契约"}}return y.validateOutcome?.(S)??{accepted:!0}}},_=wr({...Ot,store:he});return c&&await _.inspect(e.runId),{manifest:o,definition:a,identity:u,implementation:Ot,skills:l,store:he}}var kD,Rl=x(()=>{"use strict";Ga();or();q$();L$();ze();F$();wa();lr();kl();$g();Y$();rD();nD();oD();lD();yD();kD=new Map});import P3 from"node:path";async function Rf(e){let t=[],r=new Set,n=e.ownerObservation===void 0?await Fe(e.projectRoot,"native",e.run.runId,{readOnly:!0}):e.ownerObservation,i=ht({singleWriter:!0,rootDir:P3.join(Le(e.projectRoot),"sdk-runs/native")}),o=new Set;async function a(s){if(!o.has(s.runId)){o.add(s.runId);for(let c of s.actions)["pending","running","unknown"].includes(c.status)&&(r.add(s.runId),t.push({runId:s.runId,actionId:c.id,stepId:c.stepId,attempt:c.attempt,inputHash:c.inputHash,reason:"原业务任务仍待完成或由 Agent 核对结果"}));for(let c of s.children){let l=n&&n.application!=="native"?await xN(e.projectRoot,n.application,c.runId):await i.read(c.runId);if(l)["cancelled","completed"].includes(l.status)?await a(l):r.add(c.runId);else{let u=s.actions.find(d=>d.id===c.actionId);u?.type==="child_workflow"&&u.status==="cancelled"&&u.attempt===1&&!u.claim&&!u.outcome&&u.receipts.length===0&&u.reconciliations.length===0||r.add(c.runId)}}}}return await a(e.run),{quiescent:t.length===0&&r.size===0,outstandingActions:t,outstandingRuns:[...r]}}async function So(e){if(e.run.status!=="cancelled")return null;let{quiescent:t,outstandingActions:r,outstandingRuns:n}=await Rf(e),i=e.ownerObservation===void 0?await Fe(e.projectRoot,"native",e.run.runId,{readOnly:!0}):e.ownerObservation,o=t?await an(e.projectRoot):null,a=!!(o?.status==="selected"&&o.selection.change===e.run.runId&&(i?.application==="native"?o.selection.workflow==="native":i&&o.selection.workflow==="application"&&o.selection.applicationId===i.application)),s=null;return a&&(s={reason:"业务调度已取消,当前选择尚未释放;请核对工作区事务并重试清理。",inspectionCommand:"comet native doctor --json",repairCommand:"comet native doctor --repair --json",finishCommand:`comet native doctor ${e.run.runId} --repair --json`}),{status:t&&!a?"cancelled":"cancelling",reason:e.run.reason??null,quiescent:t,cleanupRequired:a,cleanup:s,outstandingActions:r,outstandingRuns:n}}async function _D(e){let t=e.cancellationObservation===void 0?await So(e):e.cancellationObservation;if(!t)return null;let r=e.state.language==="zh-CN";return{continuation:{...e.base,status:t.status,disposition:t.status==="cancelled"?"done":"blocked",mode:t.status==="cancelled"?"done":"reconcile",requiresUserDecision:!1,action:"none",commandArgs:t.status==="cancelled"?null:t.cleanupRequired?["comet","native","doctor","--json"]:["comet","native","doctor",e.state.name,"--repair"],requiredInputs:t.quiescent?[]:["original-platform-task-result"],inputOptions:[],commandAlternatives:[],runnerAction:{...e.base.runnerAction,kind:"none"},userCommunication:{required:!1,message:null,suggestedReply:null,agentInstruction:t.cleanupRequired?r?"业务调度已取消,但当前选择尚未释放,清理仍未完成。先运行全局 Native doctor 查看根变更锁的原持有者、锁龄和待恢复事务;确认原持有者已停止且达到现有接管条件后再显式修复,最后重试此任务的 doctor --repair。不得删锁或跳过原有保护。":"Scheduling is cancelled, but current selection release is still pending. Inspect global Native doctor for the root mutation lock owner, age, and unfinished transactions. Confirm the owner stopped and existing takeover conditions are met before explicit repair, then retry this change’s doctor --repair. Do not delete locks or bypass their protections.":t.quiescent?r?"业务任务已取消,代码与历史保留。原平台任务的取消和进程清理由 Agent 通过平台工具核对;Comet 不声明原进程已经停止。":"Business scheduling is cancelled; code and history are retained. The Agent must verify original task cancellation and process cleanup through the platform. Comet does not certify process termination.":r?"任务已停止派发。通过原 Agent 平台核对尚未完成的任务、实际副作用、取消及清理结果;沿用原业务任务记录,不按历史 PID 杀进程,不生成停止回执。":"Scheduling is cancelled. Inspect unfinished tasks, actual side effects, cancellation, and cleanup through their original Agent platform. Keep the original business task records; do not kill historical PIDs or create stop receipts."}},cancellation:t}}var Eo=x(()=>{"use strict";or();ze();Rl();lr();wa();Se()});function ID(e){return Number.isSafeInteger(e)&&e>=1}async function xD(e){if(!ID(e.expectedRevision))throw new Error("Native expected revision must be a positive integer");if(e.next.revision!==e.expectedRevision+1)throw new Error("Native CAS next revision must increment the expected revision exactly once");let t=await e.read();if(!ID(t.revision))throw new Error("Native current revision must be a positive integer");let r=e.equals??((n,i)=>JSON.stringify(n)===JSON.stringify(i));if(t.revision===e.next.revision&&r(t,e.next))return t;if(t.revision!==e.expectedRevision)throw e.conflict(t.revision);return await e.write(e.next),e.next}var PD=x(()=>{"use strict"});var gi,Nf=x(()=>{"use strict";gi=Object.freeze({stateRef:"runtime/run-state.json",pendingRef:"runtime/pending-action.json",trajectoryRef:"runtime/trajectory.jsonl",contextRef:"runtime/context.md",artifactsRef:"runtime/artifacts.json",checkpointRef:"runtime/checkpoints/latest.json",snapshotsRef:"runtime/skill-snapshots"})});var qg=x(()=>{"use strict"});var TD=x(()=>{"use strict"});var ON=x(()=>{"use strict";qg()});var OD=x(()=>{"use strict";qg();ON()});var B3,jD=x(()=>{"use strict";B3=dr(Ur(),1);Yn();eo();lt()});var Dde,$D=x(()=>{"use strict";Yn();lt();Dde=Number.MAX_SAFE_INTEGER});var DD=x(()=>{"use strict"});var BD=x(()=>{"use strict";iN();DD()});var WD=x(()=>{"use strict";BD()});var Yde,qD=x(()=>{"use strict";Ni();yc();WD();Yde=En("hookWritePolicy",async e=>(await uk(e))?.hook??{allow_paths:[]})});var LD=x(()=>{"use strict";qg();Yn();TD();OD();eo();jD();lt();yc();yk();$D();qD();wa();vk();ON()});var VD=x(()=>{"use strict";LD();mc()});import q3 from"path";function Ef(e,t){let r=e[t];if(typeof r!="string"||r.length===0)throw new Error(`Invalid Run state: ${t} must be a non-empty string`);return r}function Sf(e,t){let r=Ef(e,t);if(q3.isAbsolute(r)||/^(?:[A-Za-z]:|[\\/]|~)/u.test(r)||r.split(/[\\/]/u).includes(".."))throw new Error(`Invalid Run state: ${t} must stay inside the change directory`);return r}function L3(e){let t=e.run_retries??"{}",r;try{r=typeof t=="string"?JSON.parse(t):t}catch(n){throw new Error("Invalid Run state: run_retries must be a JSON object",{cause:n})}if(!r||typeof r!="object"||Array.isArray(r))throw new Error("Invalid Run state: run_retries must be a JSON object");for(let n of Object.values(r))if(!Number.isInteger(n)||Number(n)<0)throw new Error("Invalid Run state: retry counts must be non-negative integers");return r}function FD(e){if(!e.run_id)return null;let t=Ef(e,"run_id"),r=Ef(e,"skill"),n=Ef(e,"skill_version"),i=Ef(e,"skill_hash"),o=Sf(e,"pending_ref"),a=Sf(e,"trajectory_ref"),s=Sf(e,"context_ref"),c=Sf(e,"artifacts_ref"),l=Sf(e,"checkpoint_ref"),u=Number(e.iteration);if(!Number.isInteger(u)||u<0)throw new Error("Invalid Run state: iteration must be a non-negative integer");if(e.orchestration!=="deterministic"&&e.orchestration!=="adaptive")throw new Error("Invalid Run state: orchestration must be deterministic or adaptive");if(e.run_status!=="running"&&e.run_status!=="waiting"&&e.run_status!=="completed"&&e.run_status!=="failed")throw new Error("Invalid Run state: run_status is invalid");return{runId:t,skill:r,skillVersion:n,skillHash:i,orchestration:e.orchestration,currentStep:MD(e,"current_step"),iteration:u,pending:MD(e,"pending"),pendingRef:o,trajectoryRef:a,contextRef:s,artifactsRef:c,checkpointRef:l,status:e.run_status,retries:L3(e)}}var MD,zfe,HD=x(()=>{"use strict";VD();MD=(e,t)=>{let r=e[t];return r==null?null:String(r)};zfe=Number.MAX_SAFE_INTEGER});function M3(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)},r=FD(t);if(!r)throw new Error("Invalid Run state: runId must be a non-empty string");return r}function Lg(e){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Invalid Run state: stored value must be an object");let t=e,r=Object.keys(t).find(n=>!V3.has(n));if(r)throw new Error(`Invalid Run state: unknown field ${r}`);if(t.currentStep!==null&&(typeof t.currentStep!="string"||t.currentStep.length===0))throw new Error("Invalid Run state: currentStep must be a non-empty string or null");if(t.pending!==null&&(typeof t.pending!="string"||t.pending.length===0))throw new Error("Invalid Run state: pending must be a non-empty string or null");if(!t.retries||typeof t.retries!="object"||Array.isArray(t.retries))throw new Error("Invalid Run state: retries must be an object");return M3(t)}var V3,QD=x(()=>{"use strict";HD();Nf();V3=new Set(["runId","skill","skillVersion","skillHash","orchestration","currentStep","iteration","pending","pendingRef","trajectoryRef","contextRef","artifactsRef","checkpointRef","status","retries"])});import{createHash as F3}from"node:crypto";import{constants as Vg,promises as Lr}from"node:fs";import yn from"node:path";import{TextDecoder as H3}from"node:util";function _f(e,t){let r=yn.relative(e,t);return r===""||!yn.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${yn.sep}`)}function JD(e){return{dev:e.dev,ino:e.ino,birthtimeMs:e.birthtimeMs,ctimeMs:e.ctimeMs,mtimeMs:e.mtimeMs,size:e.size}}function Cf(e,t){return ot({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.mtimeMs===t.mtimeMs&&e.size===t.size}function Q3(e,t){return ot({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function Bs(e,t,r){let n=gi[t];if(r!==void 0&&r!==n)throw new Error(`Native Run ${t} ref must be ${n}`);let i=yn.resolve(e),o=yn.resolve(i,...n.slice(8).split("/"));if(!_f(i,o))throw new Error("Native Run path must stay inside its Runtime root");return o}async function UD(e){let t=await Lr.lstat(e);if(!t.isDirectory()||t.isSymbolicLink())throw new Error(`Native Run parent must be a real directory: ${e}`);return{path:e,realPath:await Lr.realpath(e),dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs}}async function jN(e,t){let r=yn.resolve(e),n=yn.resolve(t);if(!_f(r,n))throw new Error("Native Run path is outside its change");let i=[await UD(r)],o=r;for(let a of yn.relative(r,n).split(yn.sep).filter(Boolean)){o=yn.join(o,a);let s;try{s=await UD(o)}catch(c){if(c.code==="ENOENT")return null;throw c}if(!_f(i[0].realPath,s.realPath))throw new Error(`Native Run parent resolves outside its change: ${o}`);i.push(s)}return i}async function Mg(e){for(let t of e){let r=await Lr.lstat(t.path);if(!r.isDirectory()||r.isSymbolicLink()||!Q3(t,r)||await Lr.realpath(t.path)!==t.realPath)throw new Error(`Native Run parent changed during I/O: ${t.path}`)}}async function U3(e,t,r){let n=[],i=0,o=Buffer.allocUnsafe(Math.min(64*1024,t+1));for(;;){let a=t+1-i,{bytesRead:s}=await e.read(o,0,Math.min(o.length,a),null);if(s===0)break;if(i+=s,i>t)throw new Error(`${r} exceeds ${t} bytes`);n.push(Buffer.from(o.subarray(0,s)))}return Buffer.concat(n,i)}async function Nl(e,t,r,n,i){let o=await jN(e,yn.dirname(t));if(!o)return null;await i?.afterParentChainCaptured?.();let a;try{a=await Lr.lstat(t)}catch(f){if(f.code==="ENOENT")return null;throw f}if(!a.isFile()||a.isSymbolicLink())throw new Error(`${n} must be a regular file`);if(a.size>r)throw new Error(`${n} exceeds ${r} bytes`);let s=JD(a),c=await Lr.realpath(t);if(!_f(o[0].realPath,c))throw new Error(`${n} resolves outside its change`);let l=process.platform==="win32"?Vg.O_RDONLY:Vg.O_RDONLY|Vg.O_NOFOLLOW|Vg.O_NONBLOCK,u;try{u=await Lr.open(t,l)}catch(f){throw new Error(`${n} changed while opening`,{cause:f})}try{let[f,d,p]=await Promise.all([u.stat(),Lr.lstat(t),Lr.realpath(t)]);if(await Mg(o),!f.isFile()||!d.isFile()||d.isSymbolicLink()||p!==c||!Cf(s,f)||!Cf(s,d))throw new Error(`${n} changed while opening`);await i?.afterOpen?.();let m=await U3(u,r,n);await i?.beforeFinalCheck?.();let[h,g,v]=await Promise.all([u.stat(),Lr.lstat(t),Lr.realpath(t)]);if(await Mg(o),!g.isFile()||g.isSymbolicLink()||v!==c||!Cf(s,h)||!Cf(s,g))throw new Error(`${n} changed while reading`);let w;try{w=new H3("utf-8",{fatal:!0}).decode(m)}catch(y){throw new Error(`${n} is not valid UTF-8`,{cause:y})}return{text:w,target:{exists:!0,identity:s,realPath:c}}}finally{await u.close()}}async function J3(e,t,r){let n=await jN(e,yn.dirname(t));if(!n)return{exists:!1};let i;try{i=await Lr.lstat(t)}catch(a){if(a.code==="ENOENT")return{exists:!1};throw a}if(!i.isFile()||i.isSymbolicLink())throw new Error(`${r} must be a regular file`);let o=await Lr.realpath(t);if(!_f(n[0].realPath,o))throw new Error(`${r} resolves outside its change`);return await Mg(n),{exists:!0,identity:JD(i),realPath:o}}async function z3(e,t,r,n){let i=await jN(e,yn.dirname(t));if(!i){if(!r.exists)return;throw new Error(`${n} parent changed before commit`)}let o;try{o=await Lr.lstat(t)}catch(a){if(a.code==="ENOENT"&&!r.exists)return;throw new Error(`${n} changed before commit`,{cause:a})}if(!r.exists||!o.isFile()||o.isSymbolicLink()||!Cf(r.identity,o)||await Lr.realpath(t)!==r.realPath)throw new Error(`${n} changed before commit`);await Mg(i)}async function Fg(e){if(Buffer.byteLength(e.content,"utf8")>e.maxBytes)throw new Error(`${e.label} exceeds ${e.maxBytes} bytes`);let r=e.expected??await J3(e.changeDir,e.file,e.label);if(r.exists&&r.identity.size>e.maxBytes)throw new Error(`${e.label} exceeds ${e.maxBytes} bytes`);await qe(e.file,e.content,{containedRoot:e.changeDir,beforeCommit:async()=>{await e.hooks?.beforeCommit?.(),await z3(e.changeDir,e.file,r,e.label)}});let n=await Nl(e.changeDir,e.file,e.maxBytes,e.label);if(!n||n.text!==e.content)throw new Error(`${e.label} commit could not be verified`)}function K3(e,t){try{return JSON.parse(e)}catch(r){throw new Error(`${t} contains invalid JSON`,{cause:r})}}function zD(e){return`${JSON.stringify(e,null,2)}
|
|
317
|
+
`}function $N(e){return Lg(e)}async function Sl(e,t){let r=Bs(e,"stateRef"),n=await Nl(e,r,Vr.runStateBytes,"Native Run state",t);return n?Lg(K3(n.text,"Native Run state")):null}async function Hg(e,t,r){let n=Lg(t);await Fg({changeDir:e,file:Bs(e,"stateRef"),content:zD(n),maxBytes:Vr.runStateBytes,label:"Native Run state",hooks:r})}async function Ws(e,t,r){let n=Bs(e,"trajectoryRef",t),i=await Nl(e,n,Vr.trajectoryBytes,"Native Run trajectory",r);if(!i)return[];let o=i.text.split(/\r?\n/u).map((a,s)=>({line:a,number:s+1})).filter(({line:a})=>a.length>0);if(o.length>Vr.trajectoryEvents)throw new Error(`Native Run trajectory exceeds ${Vr.trajectoryEvents} events`);return o.map(({line:a,number:s})=>{try{return JSON.parse(a)}catch(c){throw new Error(`Invalid Native Run trajectory event at line ${s}`,{cause:c})}})}async function KD(e,t,r){return(await Nl(e,Bs(e,"trajectoryRef",t),Vr.trajectoryBytes,"Native Run trajectory",r))?.text??null}async function GD(e,t,r,n,i){if(!/^[a-f0-9]{64}$/u.test(n))throw new Error("Native Run trajectory expected hash is invalid");let o=Bs(e,"trajectoryRef",t),a=await Nl(e,o,Vr.trajectoryBytes,"Native Run trajectory");if(!a)throw new Error("Native Run trajectory disappeared before repair");if(F3("sha256").update(a.text,"utf8").digest("hex")!==n)throw new Error("Native Run trajectory changed before repair");await Fg({changeDir:e,file:o,content:r,maxBytes:Vr.trajectoryBytes,label:"Native Run trajectory",expected:a.target,hooks:i})}async function YD(e,t,r,n){let i=Bs(e,"trajectoryRef",t),o=`${JSON.stringify(r)}
|
|
318
|
+
`;if(Buffer.byteLength(o,"utf8")>Vr.trajectoryEventBytes)throw new Error(`Native Run trajectory event exceeds ${Vr.trajectoryEventBytes} bytes`);let a=await Nl(e,i,Vr.trajectoryBytes,"Native Run trajectory");if((a?a.text.split(/\r?\n/u).filter(c=>c.length>0).length:0)>=Vr.trajectoryEvents)throw new Error(`Native Run trajectory exceeds ${Vr.trajectoryEvents} events`);await Fg({changeDir:e,file:i,content:`${a?.text??""}${o}`,maxBytes:Vr.trajectoryBytes,label:"Native Run trajectory",expected:a?.target??{exists:!1},hooks:n})}async function XD(e,t,r,n){await Fg({changeDir:e,file:Bs(e,"checkpointRef",t),content:zD(r),maxBytes:Vr.checkpointBytes,label:"Native Run checkpoint",hooks:n})}var Vr,If=x(()=>{"use strict";Nf();QD();dt();hc();Vr={runStateBytes:Number.MAX_SAFE_INTEGER,trajectoryBytes:Number.MAX_SAFE_INTEGER,trajectoryEvents:4096,trajectoryEventBytes:Number.MAX_SAFE_INTEGER,checkpointBytes:Number.MAX_SAFE_INTEGER,pendingActionBytes:Number.MAX_SAFE_INTEGER,contextBytes:Number.MAX_SAFE_INTEGER,artifactsBytes:Number.MAX_SAFE_INTEGER}});import{createHash as G3}from"crypto";import Y3 from"path";function DN(e){return G3("sha256").update(e).digest("hex")}function Z3(e,t){if(!X3.test(t))throw new Error(`Invalid Native change name: ${t}`);return Y3.join(hn(e,t),"trajectory.jsonl")}function e8(e){let t=e.split(/\n/u),r=0;for(let n=0;n<t.length;n+=1){let i=t[n].endsWith("\r")?t[n].slice(0,-1):t[n];if(i.length!==0){r=n+1;try{JSON.parse(i)}catch(o){return{status:"invalid",line:n+1,message:o.message}}}}return{status:"valid",count:r}}function t8(e,t){if(/Unexpected end|Unterminated string/iu.test(e.message))return!0;let r=/position (\d+)/iu.exec(e.message)?.[1];return r!==void 0&&Number(r)>=Math.max(0,t.length-1)}function r8(e,t){let r=t.lastIndexOf(10),n=t.subarray(0,r+1),i=e8(n.toString("utf8"));if(i.status==="invalid")return{status:"invalid",file:e,line:i.line,message:i.message};if(r===t.length-1)return{status:"clean",file:e};let o=t.subarray(r+1),a=o.toString("utf8"),s=i.count+1,c,l;try{JSON.parse(a.endsWith("\r")?a.slice(0,-1):a),c="missing-newline",l=Buffer.concat([t,Buffer.from(`
|
|
319
|
+
`)])}catch(f){if(!t8(f,a))return{status:"invalid",file:e,line:s,message:f.message};c="incomplete-json",l=n}return{inspection:{status:"repairable",file:e,reason:c,line:s,originalHash:DN(t),targetHash:DN(l),tailHash:DN(o),discardedBytes:c==="incomplete-json"?o.length:0},targetContent:l.toString("utf8")}}async function ZD(e,t){let r=Z3(e,t);await ft(Ve(e,r),r);let n=hn(e,t),i=await KD(n,gi.trajectoryRef).catch(o=>{if(o.code==="ENOENT")return null;throw o});return i===null?{status:"clean",file:r}:r8(r,Buffer.from(i))}async function Ug(e,t){let r=await ZD(e,t);return"inspection"in r?r.inspection:r}async function Jg(e,t){let r=await Ug(e,t);if(r.status!=="clean")throw new Qg(r)}async function eB(e,t,r){return $e(e,async()=>{let n=await ZD(e,t);if(!("inspection"in n)){if(n.status==="clean")return null;throw new Qg(n)}try{await GD(hn(e,t),gi.trajectoryRef,n.targetContent,n.inspection.originalHash,{beforeCommit:r?.beforeCommit})}catch(o){throw/changed (?:before|while)/iu.test(o.message)?new Error(`Native trajectory changed while preparing tail repair for ${t}; inspect it again before retrying`,{cause:o}):o}if((await Ug(e,t)).status!=="clean")throw new Error(`Native trajectory tail repair did not produce a clean file for ${t}`);return n.inspection})}var X3,Qg,zg=x(()=>{"use strict";Nf();St();He();If();X3=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,Qg=class extends Error{constructor(r){super(r.status==="repairable"?`Native trajectory has an incomplete final line at ${r.file}:${r.line}; run doctor --repair`:`Native trajectory is invalid at ${r.file}:${r.line}: ${r.message}`);this.inspection=r;this.name="NativeTrajectoryRepairRequiredError"}inspection;code="native-trajectory-tail-repair-required"}});import{createHash as n8}from"node:crypto";import{promises as tB}from"node:fs";import qs from"node:path";function oB(e,t){let r=qs.relative(e,t);return qs.isAbsolute(r)||r===".."||r.startsWith(`..${qs.sep}`)?null:r.replaceAll("\\","/")||"."}function aB(e){return Array.from(e).some(t=>{let r=t.codePointAt(0)??0;return r<=31||r===127})}function qN(e,t){if(e.length===0||aB(e)||e.includes("\\")||qs.posix.isAbsolute(e)||/^(?:[A-Za-z]:|~)/u.test(e)||e.split("/").includes(".."))throw new Error(`${t} must be a portable project-relative path`);let r=qs.posix.normalize(e);if(r!==e||r===".."||r.startsWith("../"))throw new Error(`${t} must be a normalized project-relative path`);return r}function BN(e,t){return n8("sha256").update(`${e}
|
|
320
|
+
${t}`).digest("hex")}async function nB(e,t,r){let n=await tB.realpath(e),i=await tB.lstat(n);if(!i.isDirectory()||i.isSymbolicLink())throw new Error("Native workspace identity requires a real directory");let o=iB==="win32"?qs.normalize(n).toLowerCase():n;return{physical:BN(t,`${o}
|
|
321
|
+
${i.dev}
|
|
322
|
+
${i.ino}
|
|
323
|
+
${i.birthtimeMs}`),path:BN(r,o)}}async function sB(e){let t=oB(e.projectRoot,e.nativeRoot);if(!t)throw new Error("Native root is outside the project root");qN(t,"Native workspace root ref");let[r,n]=await Promise.all([nB(e.projectRoot,"comet.native.workspace-project-root.v2","comet.native.workspace-project-root-path.v2"),nB(e.nativeRoot,"comet.native.workspace-native-root.v2","comet.native.workspace-native-root-path.v2")]);return{nativeRootRef:t,projectRootId:r.physical,nativeRootId:n.physical,projectRootPathId:r.path,nativeRootPathId:n.path}}function o8(e){if(typeof e!="string")throw new Error("Native workspace capturedAt is invalid");let t=new Date(e);if(!Number.isFinite(t.getTime())||t.toISOString()!==e)throw new Error("Native workspace capturedAt is invalid");return e}function WN(e,t){if(e===null)return null;if(typeof e!="string"||e.length===0||e.trim()!==e||aB(e))throw new Error(`${t} must be a non-empty branch name or null`);return e}function cB(e){if(!new Set(["current","branch","worktree"]).has(e.isolation))throw new Error("Native workspace isolation must be current, branch, or worktree");if(WN(e.changeBranch,"Native workspace change branch"),WN(e.targetBranch,"Native workspace target branch"),(e.isolation==="branch"||e.isolation==="worktree")&&(e.changeBranch===null||e.targetBranch===null))throw new Error("Native isolated workspace requires change and target branches")}function a8(e){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Native workspace Git provenance must be an object");let t=e,r=new Set(["provider","baseCommit","targetBranch","targetCommit"]),n=Object.keys(t).filter(i=>!r.has(i));if(n.length>0)throw new Error(`Native workspace Git provenance has unknown field(s): ${n.join(", ")}`);if(t.provider!=="git"||typeof t.baseCommit!="string"||!rB.test(t.baseCommit)||typeof t.targetCommit!="string"||!rB.test(t.targetCommit))throw new Error("Native workspace Git provenance is invalid");WN(t.targetBranch,"Native workspace Git target branch")}function Kg(e){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Native workspace identity must be an object");let t=e,r=new Set(["schema","capturedAt","capturedRevision","nativeRootRef","projectRootId","nativeRootId","projectRootPathId","nativeRootPathId","sessionHash","git","isolation","changeBranch","targetBranch","finish"]),n=Object.keys(t).filter(a=>!r.has(a));if(n.length>0)throw new Error(`Native workspace identity has unknown field(s): ${n.join(", ")}`);if(t.schema!=="comet.native.workspace.v2"&&t.schema!=="comet.native.workspace.v3")throw new Error("Unsupported Native workspace identity");if(!Number.isSafeInteger(t.capturedRevision)||t.capturedRevision<1||typeof t.nativeRootRef!="string"||!xf.test(String(t.projectRootId))||!xf.test(String(t.nativeRootId)))throw new Error("Native workspace identity is invalid");o8(t.capturedAt),qN(t.nativeRootRef,"Native workspace root ref");let i=t.projectRootPathId!==void 0,o=t.nativeRootPathId!==void 0;if(i!==o)throw new Error("Native workspace path identities must be provided together");if(i&&!xf.test(String(t.projectRootPathId))||o&&!xf.test(String(t.nativeRootPathId)))throw new Error("Native workspace path identity is invalid");if(t.sessionHash!==void 0&&!xf.test(String(t.sessionHash)))throw new Error("Native workspace session hash is invalid");if(t.git!==void 0&&a8(t.git),t.schema==="comet.native.workspace.v2"){if(t.isolation!==void 0||t.changeBranch!==void 0||t.targetBranch!==void 0||t.finish!==void 0)throw new Error("Native workspace v2 identity cannot contain a workspace binding");return}if(typeof t.isolation!="string"||t.changeBranch===void 0||t.targetBranch===void 0||t.finish===void 0)throw new Error("Native workspace v3 identity requires a workspace binding");if(cB(t),t.finish!==null&&!new Set(["merge","push","pull-request","keep"]).has(t.finish))throw new Error("Native workspace finish must be merge, push, pull-request, keep, or null")}function lB(e,t){return qs.join(hn(e,t),"workspace.json")}function s8(e,t){let r=lB(e,t),n=Ve(e,r),i=oB(n,r);if(!i||i===".")throw new Error("Native workspace file escaped its root");return{root:n,ref:qN(i,"Native workspace file ref")}}async function c8(e,t){try{let r=s8(e,t),n=await Pe({root:r.root,ref:r.ref,maxBytes:i8});return JSON.parse(n.text)}catch(r){if(r.code==="ENOENT")return null;throw r}}async function l8(e){if(!Number.isSafeInteger(e.revision)||e.revision<1)throw new Error("Native workspace revision must be a positive integer");let t=await sB(e.paths),r=ue(e.paths.projectRoot),n=r.isGitWorktree?pe(e.paths.projectRoot,"HEAD"):null,i=e.binding?.targetBranch??r.currentBranch,o=i==null?null:pe(e.paths.projectRoot,i),a=n!==null&&i!==null&&i!==void 0&&o!==null?{provider:"git",baseCommit:n,targetBranch:i,targetCommit:o}:void 0,s=(e.now??new Date).toISOString();if(e.finish&&!e.binding)throw new Error("Native workspace finish requires a workspace binding");e.binding&&cB(e.binding);let c={capturedAt:s,capturedRevision:e.revision,...t,...a?{git:a}:{},...e.sessionId?{sessionHash:BN("comet.native.workspace-session.v2",`${t.projectRootId}
|
|
324
|
+
${t.nativeRootId}
|
|
325
|
+
${e.sessionId}`)}:{}},l=e.binding?{schema:"comet.native.workspace.v3",...c,...e.binding,finish:e.finish??null}:{schema:"comet.native.workspace.v2",...c};return Kg(l),l}async function uB(e){let t=await l8(e),r=lB(e.paths,e.name),n=Ve(e.paths,r);return await ft(n,r),await Bt(r,t,{containedRoot:n}),t}async function El(e,t){let r=await c8(e,t);return r===null||r&&typeof r=="object"&&!Array.isArray(r)&&r.schema==="comet.native.workspace.v1"?null:(Kg(r),r)}async function LN(e){Kg(e.identity);let t=await sB(e.paths),r=[],n=[];return t.nativeRootRef!==e.identity.nativeRootRef&&r.push("native-root-ref"),e.identity.projectRootPathId&&e.identity.nativeRootPathId?(t.projectRootPathId!==e.identity.projectRootPathId&&r.push("project-root-path"),t.nativeRootPathId!==e.identity.nativeRootPathId&&r.push("native-root-path")):(t.projectRootId!==e.identity.projectRootId&&r.push("project-root-legacy-identity"),t.nativeRootId!==e.identity.nativeRootId&&r.push("native-root-legacy-identity")),iB==="win32"&&r.length>0&&r.every(o=>o==="project-root-legacy-identity"||o==="native-root-legacy-identity")?n.push("workspace-inspection-unavailable"):r.length>0&&n.push("workspace-root-changed"),{state:n.length===0?"aligned":n.includes("workspace-root-changed")?"drifted":"unknown",findingCodes:n,driftComponents:r}}async function Gg(e){if(Kg(e.identity),e.identity.schema==="comet.native.workspace.v2")return{state:"legacy",code:"workspace-binding-legacy",message:"Legacy Native workspace metadata has no isolation binding"};if((await LN(e)).state==="drifted")return{state:"drifted",code:"workspace-binding-root-changed",message:"Native change is being accessed from a different working directory"};let r=ue(e.paths.projectRoot);return e.identity.changeBranch===null?r.isGitWorktree?{state:"drifted",code:"workspace-branch-changed",message:"Native change was created outside Git but is now being accessed inside Git"}:{state:"aligned",code:null,message:null}:r.isGitWorktree?r.currentBranch!==e.identity.changeBranch?{state:"drifted",code:"workspace-branch-changed",message:`Native change is bound to branch ${e.identity.changeBranch}, but the current branch is ${r.currentBranch??"detached HEAD"}`}:e.identity.isolation==="worktree"&&!r.isSecondaryWorktree?{state:"drifted",code:"workspace-kind-changed",message:"Native change is bound to a linked Git worktree"}:{state:"aligned",code:null,message:null}:{state:"drifted",code:"workspace-vcs-unavailable",message:"Native change requires its bound Git working directory"}}async function dB(e,t){let r=await El(e,t);if(r===null)return null;let n=await Gg({paths:e,identity:r});if(n.state==="drifted")throw new Error(`${n.code}: ${n.message}`);return r}var xf,rB,i8,iB,Pf=x(()=>{"use strict";it();dt();Er();St();He();xf=/^[a-f0-9]{64}$/u,rB=/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u,i8=Number.MAX_SAFE_INTEGER,iB=process.platform});import{promises as d8}from"fs";import ba from"path";function Fi(e,t){sl(t);let r=ba.join(e.changesDir,t);if(!yt(e.changesDir,r))throw new Error("Native change path escaped");return r}async function Xg(e,t){let r=hn(e,t),n=ba.join(r,"schema-migration.json");await ft(yt(e.runtimeDir,n)?e.runtimeDir:e.nativeRoot,n);try{return await d8.lstat(n),!0}catch(i){if(i.code==="ENOENT")return!1;throw i}}async function Zg(e,t=ba.dirname(e)){let r=ba.relative(t,e).split(ba.sep).join("/"),n=await Pe({root:t,ref:r,maxBytes:null,includeHash:!1}),i=(0,Yg.parseDocument)(n.text,{uniqueKeys:!0});if(i.errors.length>0)throw new Error(`Invalid Native change file ${e}: ${i.errors[0].message}`);return i.toJS()}async function f8(e,t){let r=ba.join(Fi(e,t),Vn);await ft(e.nativeRoot,r);let n=eg(await Zg(r,e.nativeRoot));if(n.state&&n.state.name!==t)throw new Error(`Native change directory/name mismatch: ${t}`);return await Xg(e,t)?{status:"migration-required",schema:n.schema,minimumRuntimeVersion:n.minimumRuntimeVersion,state:n.state,message:`Native schema migration is incomplete for ${t}; run doctor --repair`}:n}async function Tf(e,t){let r=ba.join(Fi(e,t),Vn);await ft(e.nativeRoot,r);let n=eg(await Zg(r,e.nativeRoot));if(n.state&&n.state.name!==t)throw new Error(`Native change directory/name mismatch: ${t}`);return n}async function Aa(e,t){let r=await f8(e,t);if(r.status==="migration-required")throw new bs(t,r.schema);if(r.status==="runtime-incompatible"||!r.state)throw new ci(r.schema,r.minimumRuntimeVersion);return await dB(e,t),r.state}async function fB(e,t,r){let n={...t,schema:si,minimum_runtime_version:3,revision:r+1},i=await xD({expectedRevision:r,next:n,read:async()=>{let o=li(await Zg(e));if(o.name!==t.name)throw new Error(`Native change file/name mismatch: ${t.name}`);return o},write:o=>qe(e,(0,Yg.stringify)(Yd(o))),equals:(o,a)=>JSON.stringify(Yd(o))===JSON.stringify(Yd(a)),conflict:o=>new ws(t.name,r,o)});return Object.assign(t,i),i}async function pB(e,t,r){if(await Nc(e.projectRoot),await Xg(e,t.name))throw new bs(t.name,t.schema);if((await Aa(e,t.name)).verification_protocol!==t.verification_protocol)throw new Error("Native verification protocol changed outside a revisioned state transition");await Jg(e,t.name);let i=ba.join(Fi(e,t.name),Vn);return await ft(e.nativeRoot,i),fB(i,t,r)}async function mB(e,t){return fB(e,t,t.revision)}async function hB(e){return li(await Zg(e))}var Yg,Xpe,Hi=x(()=>{"use strict";tl();tl();nN();Ni();Yg=dr(Ur(),1);it();ze();lr();Rl();Eo();rN();Er();dt();ul();Et();St();Se();He();_s();PD();zg();Pf();zd();Xd();Xd();Xpe=nf("en")});import{createHash as p8}from"crypto";function Rr(e){return p8("sha256").update(e).digest("hex")}var Ra=x(()=>{"use strict"});import m8 from"path";function VN(e){return{valid:e.length===0,findings:e}}function gB(e,t){return VN(e.trim()?[]:[{code:"spec-document-empty",message:"Native target Spec is empty: "+t,path:t}])}function h8(e){let t=new Set(["blocker","blocking","coverage","decision","open_question","question","requirement","requirements","source","source_coverage","state","status","决策","来源","覆盖","问题","状态","需求","阻塞"]),r={marker:null,length:0};for(let n of e.split(/\r?\n/u)){if(g8(n,r)!==null||r.marker!==null)continue;let i=n.trim();if(/^(?:[-*+]\s+|\d+[.)]\s+)(?:\[[ xX]\]\s+)?\[blocking\](?=$|[\s::—-])/iu.test(i)||i.includes("|")&&i.split("|").some(a=>/^\s*\[blocking\](?=$|[\s::—-])/iu.test(a)))return!0;let o=i.match(/^([\p{L}\p{N}_./-]+)\s*[::]\s*\[blocking\](?=$|[\s::—-])/iu);if(o){let a=o[1]?.toLocaleLowerCase("en-US")??"";if(t.has(a)||/[./_-]/u.test(a))return!0}}return!1}function g8(e,t){let r=/^ {0,3}(`{3,}|~{3,})/u.exec(e);if(r===null)return null;let n=r[1]??"",i=n[0];return t.marker===null?(t.marker=i,t.length=n.length,"opened"):i===t.marker&&n.length>=t.length&&e.trim()===n?(t.marker=null,t.length=0,"closed"):null}async function vB(e,t,r={}){let n;try{n=(await Pe({root:e,ref:t,maxBytes:r.maxBytes??null,includeHash:!1})).text}catch(o){return VN([{code:"brief-missing",message:o.message,path:t}])}let i=[];return n.trim()||i.push({code:"brief-empty",message:"Native brief is empty: "+t,path:t}),h8(n)&&i.push({code:"brief-blocking-question",message:"Brief has a blocking open question",path:t}),VN(i)}function ev(e,t){return m8.join(e.specsDir,t,"spec.md")}var Cl,tv=x(()=>{"use strict";Er();Hi();Ra();He();Cl=class extends Error{constructor(r,n,i){super(r);this.findings=n;this.change=i;this.name="NativeDocumentConstraintError"}findings;change}});function Ls(e,t,r){if(e.phase!=="verify")return[];let n=[];return e.status==="await-user"&&(t.stepId==="verify.stop"&&["await-user","resolve-verifier-blocker"].includes(e.loop.next_action??"")?(e.loop.next_action==="resolve-verifier-blocker"&&n.push({action:"resolve-verifier-blocker",choice:"retry"}),n.push({action:"revise-implementation",choice:"repair"})):t.stepId==="verify.confirm"&&e.loop.next_action==="confirm-skill-coordinated-pass"&&(n.push({action:"accept-result",choice:"approved"},{action:"revise-implementation",choice:"rejected"}),t.choices.includes("reverify")&&n.push({action:"retry-verifier",choice:"reverify"}))),t.stepId==="verify.retry"&&e.status==="blocked"&&e.loop.next_action==="retry-verifier"&&n.push({action:"retry-verifier",choice:"retry"}),n.filter(({choice:i})=>t.choices.includes(i))}function HN(e,t){return["failed","cancelled","completed"].includes(e.status)?[]:e.waits.filter(r=>r.status==="pending").flatMap(r=>Ls(t,r,e).map(n=>({...n,wait:r})))}var QN=x(()=>{"use strict"});function jf(e){return e.replace(S8,"$1 [REDACTED]").replace(E8,"[REDACTED PRIVATE KEY]").replace(C8,"$1[REDACTED]@").replace(_8,"[REDACTED TOKEN]").replace(I8,'$1"[REDACTED]"').replace(x8,"$1$2$1$3$4[REDACTED]$4").replace(P8,"$1$2[REDACTED]")}var S8,E8,C8,_8,I8,x8,P8,UN=x(()=>{"use strict";S8=/\b(Bearer|Basic)\s+[^\s"']+/giu,E8=/-----BEGIN(?: [A-Z0-9]+)? PRIVATE KEY-----[\s\S]*?-----END(?: [A-Z0-9]+)? PRIVATE KEY-----/gu,C8=/(https?:\/\/)[^\s/@:]+:[^\s/@]+@/giu,_8=/\b(?:sk-(?:proj-)?[A-Za-z0-9_-]{16,}|gh[pousr]_[A-Za-z0-9_]{16,}|github_pat_[A-Za-z0-9_]{16,}|AKIA[A-Z0-9]{16}|AIza[A-Za-z0-9_-]{20,})\b/gu,I8=/("(?:[a-z0-9]+[_-])*(?:api[_-]?key|access[_-]?token|auth[_-]?token|client[_-]?secret|secret(?:[_-]?access)?[_-]?key|private[_-]?key|token|password|passwd|secret|authorization|cookie|set[_-]?cookie)"\s*:\s*)"(?:\\[\s\S]|[^"\\\r\n])*"/giu,x8=/(["'])((?:[a-z0-9]+[_-])*(?:api[_-]?key|access[_-]?token|auth[_-]?token|client[_-]?secret|secret(?:[_-]?access)?[_-]?key|private[_-]?key|token|password|passwd|secret|authorization|cookie|set[_-]?cookie))\1(\s*:\s*)(["'])[^\r\n]*?\4/giu,P8=/\b((?:[a-z0-9]+[_-])*(?:api[_-]?key|access[_-]?token|auth[_-]?token|client[_-]?secret|secret(?:[_-]?access)?[_-]?key|private[_-]?key|token|password|passwd|secret|authorization|cookie|set[_-]?cookie))\b(\s*[:=]\s*)(?:"[^"]*"|'[^']*'|[^\s,;"']+)/giu});import{randomUUID as T8}from"node:crypto";function cn(e){return Ct(jf(e))}function kn(e){return e.state_version+1}function j8(e,t,r){let n=[...e];if(new Set(n).size!==n.length)throw new Error(`${r} contains duplicate IDs`);let i=new Set(t.map(({id:a})=>a)),o=n.filter(a=>!i.has(a));if(o.length>0)throw new Error(`${r} contains unknown IDs: ${o.join(", ")}`);return n}function CB(e){return e.map(t=>({...t,result:"pending",reason:null}))}function _B(e){return e.acceptance.filter(({result:t})=>t==="pending").map(({id:t})=>t)}function $8(e){return(e??[]).map(t=>({name:cn(t.name),result:t.result,note:t.note?cn(t.note):null}))}function Il(e){return{goal_cycle:e.state.loop.goal_cycle,iteration:e.state.loop.iteration,attempt:e.state.loop.attempt,outcome:e.outcome,unresolved_ids:e.unresolvedIds??[],summary:cn(e.summary),completed_at:e.completedAt}}function JN(e){let t=M(e.state);if(t.phase!=="shape"||t.status!=="await-user"||t.loop.stage!=="await-user"||t.loop.next_action!=="confirm-shape")throw new Error("Native acceptance can only be confirmed from the persisted Shape confirmation boundary");if(e.acceptance.length===0)throw new Error("Native acceptance cannot be empty");let r=e.acceptance.map(({id:n})=>n);if(new Set(r).size!==r.length)throw new Error("Native acceptance IDs must be unique");return M({...t,phase:"build",status:"active",state_version:kn(t),loop:{...t.loop,stage:"building",iteration:1,attempt:0,next_action:"submit-builder-candidate"},acceptance:e.acceptance.map(n=>({...n,result:"pending",reason:null}))})}function zN(e){let t=M(e.state);if(t.phase!=="shape"||t.status!=="active"||t.loop.stage!=="shape")throw new Error("Native Shape confirmation can only be prepared from active Shape");if(e.acceptance.length===0)throw new Error("Native acceptance cannot be empty");let r=e.acceptance.map(({id:n})=>n);if(new Set(r).size!==r.length)throw new Error("Native acceptance IDs must be unique");return M({...t,status:"await-user",state_version:kn(t),loop:{...t.loop,stage:"await-user",next_action:"confirm-shape"},acceptance:e.acceptance.map(n=>({...n,result:"pending",reason:null}))})}function KN(e){let t=M(e.state),{input:r}=e;if(t.phase!=="build"||t.status!=="active")throw new Error("Native candidate can only be submitted from active Build");if(!Ej(r.identity))throw new Error("Native Builder identity must come from the trusted Runner channel");if(r.review){if(r.review.status!=="passed")throw new Error("Native Builder review status must be passed when supplied");if(r.review.reviewerExecutionRef===r.identity.executionRef)throw new Error("Native reviewer execution ref must differ from the Builder execution ref")}let n=j8(r.addressedAcceptanceIds,t.acceptance,"Native Builder addressed acceptance"),i=[],o,a;if(r.acceptanceReview!==void 0)try{a=Nm(r.acceptanceReview,t.acceptance,"acceptanceReview")}catch(l){o=l,i.push(l instanceof Error?l.message:String(l))}else if(e.requireAcceptanceReview!==!1)try{Ju(t.acceptance,void 0)}catch(l){o=l,i.push(l instanceof Error?l.message:String(l))}for(let[l,u]of(r.checks??[]).entries())(!u||typeof u.name!="string")&&i.push("Native Builder checks["+l+"].name must be a string"),(!u||!["passed","failed","not-run"].includes(String(u.result)))&&i.push("Native Builder checks["+l+"].result must be passed, failed, or not-run; received "+JSON.stringify(u?.result)),u?.note!=null&&typeof u.note!="string"&&i.push("Native Builder checks["+l+"].note must be a string or null");if(i.length===1&&o instanceof Zo)throw o;if(i.length)throw new Error(i.join(`
|
|
326
|
+
`)+`
|
|
327
|
+
Correct the reported business fields and submit a new outcomeId using the original claim.`);let s=CB(t.acceptance),c=(r.now??new Date).toISOString();return M({...t,phase:"verify",state_version:kn(t),verification_result:"pending",verification_report:null,verification:null,blockers:[],acceptance:s,builder_handoff:{candidate_id:r.candidateId??T8(),identity_provider:r.identity.identityProvider,builder_execution_ref:r.identity.executionRef,iteration:t.loop.iteration,summary:cn(r.summary),addressed_acceptance_ids:n,acceptance_review:a,checks:$8(r.checks),checks_truncated:!1,known_limits:(r.knownLimits??[]).map(l=>cn(l)),known_limits_truncated:!1,review:r.review?{status:"passed",summary:cn(r.review.summary),reviewer_execution_ref:r.review.reviewerExecutionRef}:null,submitted_at:c},loop:{...t.loop,stage:"verify-ready",attempt:0,execution_failure_count:0,next_action:"run-required-checks-and-dispatch-verifier"}})}function Ui(e){let t=M(e);if(t.phase!=="verify"||t.status!=="active"||t.loop.stage!=="verify-ready"||t.builder_handoff===null)throw new Error("Native Verifier attempt requires a current Builder candidate");return M({...t,state_version:kn(t),verification:null,loop:{...t.loop,attempt:t.loop.attempt+1,next_action:"await-verifier-result"}})}function D8(e){return{candidate_id:e.envelope.candidateId,identity_provider:e.envelope.identityProvider,verifier_execution_ref:e.envelope.verifierExecutionRef,iteration:e.state.loop.iteration,attempt:e.state.loop.attempt,assurance:e.envelope.verifierExecutionRef===e.state.builder_handoff?.builder_execution_ref?"self-reviewed":e.envelope.identityProvider===$r?"skill-coordinated":"host-attested",verdict:e.response.result.verdict,checks:[],summary:cn(e.response.result.summary),risks:e.response.result.risks.map(t=>cn(t)),risks_truncated:!1,completed_at:e.completedAt}}function GN(e){let t=M(e.state);if(t.phase!=="verify"||t.builder_handoff===null||t.loop.attempt<1)throw new Error("Native change is not awaiting a Verifier result");let r=_B(t);if(r.length===0)throw new Error("Native Verifier attempt has no pending acceptance scenarios");let n=Ij({envelope:e.envelope,binding:{candidateId:t.builder_handoff.candidate_id,identityProvider:t.builder_handoff.identity_provider,builderExecutionRef:t.builder_handoff.builder_execution_ref,requireIndependentSession:e.requireIndependentSession,iteration:t.loop.iteration,attempt:t.loop.attempt,acceptanceIds:r,knownAcceptanceIds:t.acceptance.map(({id:d})=>d),previouslyPassedAcceptanceIds:t.acceptance.filter(({result:d})=>d==="passed").map(({id:d})=>d),requiredChecksPassed:(e.reportedChecks??[]).every(({result:d})=>d==="passed")}});if(!Number.isSafeInteger(e.maxVerifyFailures)||e.maxVerifyFailures<1)throw new Error("Native max Verify failures must be a positive integer");let i=(e.now??new Date).toISOString(),o=new Map(n.result.acceptance.map(d=>[d.id,d])),a=t.acceptance.map(d=>{let p=o.get(d.id);return p?{...d,result:p.result,reason:cn(p.reason)}:d}),s=a.filter(({result:d})=>d==="failed"||d==="blocked").map(({id:d})=>d),c=D8({state:t,envelope:e.envelope,response:n,completedAt:i});if(e.reportedChecks&&(c.reported_checks=e.reportedChecks),n.result.verdict==="pass"){let d=vn({...t,acceptance:a,verification:c},Il({state:t,outcome:"pass",summary:n.result.summary,completedAt:i})),p=t.builder_handoff.identity_provider===$r;return{response:n,state:M({...d,phase:p?"verify":"archive",status:p?"await-user":"active",state_version:kn(t),verification_result:"pass",verification_report:"verification.md",blockers:p?[{owner:"user",reason:cn(e.requireIndependentSession===!1?"Verification passed; user acceptance is required before Archive.":"The generic Skill bridge cannot prove an independent Verifier execution; user confirmation is required before Archive."),acceptance_ids:[],resolution_action:"await-user"}]:[],loop:{...t.loop,stage:p?"await-user":"archive-ready",execution_failure_count:0,previous_unresolved_ids:[],no_progress_count:0,next_action:p?"confirm-skill-coordinated-pass":"archive"}})}}if(n.result.verdict==="blocked"){let d=vn({...t,acceptance:a,verification:c},Il({state:t,outcome:"blocked",unresolvedIds:s,summary:n.result.summary,completedAt:i}));return{response:n,state:M({...d,status:"await-user",state_version:kn(t),verification_result:"blocked",verification_report:"verification.md",blockers:[{owner:"user",reason:cn(n.result.summary),acceptance_ids:s,resolution_action:"resolve-verifier-blocker"}],loop:{...t.loop,stage:"await-user",execution_failure_count:0,previous_unresolved_ids:s,next_action:"resolve-verifier-blocker"}})}}let l=t.loop.failed_iteration_count+1,u=l>=e.maxVerifyFailures,f=vn({...t,acceptance:a,verification:c},Il({state:t,outcome:"fail",unresolvedIds:s,summary:n.result.summary,completedAt:i}));return{response:n,state:M({...f,phase:u?"verify":"build",status:u?"await-user":"active",state_version:kn(t),verification_result:"fail",verification_report:"verification.md",builder_handoff:t.builder_handoff,blockers:u?[{owner:"user",reason:cn("Native verification reached the configured failed iteration limit."),acceptance_ids:s,resolution_action:"await-user"}]:[],loop:{...t.loop,stage:u?"await-user":"repairing",iteration:u?t.loop.iteration:t.loop.iteration+1,attempt:u?t.loop.attempt:0,failed_iteration_count:l,no_progress_count:0,stop_reason:u?"budget":void 0,execution_failure_count:0,previous_unresolved_ids:s,next_action:u?"await-user":"repair-failed-acceptance"}})}}function YN(e){let t=M(e);if(t.phase!=="verify"||t.status!=="await-user"||t.verification_result!=="pass"||t.verification===null||t.builder_handoff?.identity_provider!==$r||t.loop.stage!=="await-user"||t.loop.next_action!=="confirm-skill-coordinated-pass")throw new Error("Native change is not awaiting Skill-coordinated pass confirmation");return M({...t,phase:"archive",status:"active",state_version:kn(t),blockers:[],loop:{...t.loop,stage:"archive-ready",next_action:"archive"}})}function XN(e,t){let r=M(e);if(r.phase!=="verify"||r.status!=="await-user"||r.verification_result!=="blocked"||r.verification?.verdict!=="blocked"||r.verification.assurance==="semantic-verification-unavailable"||r.loop.stage!=="await-user"||r.loop.next_action!=="resolve-verifier-blocker"||!r.blockers.some(({resolution_action:i})=>i==="resolve-verifier-blocker"))throw new Error("Native change is not awaiting resolution of a semantic Verifier blocker");let n=vn(r,Il({state:r,outcome:"recovery",summary:t?.reason??"Resolved the semantic Verifier blocker and resumed verification.",completedAt:(t?.now??new Date).toISOString()}));return M({...n,status:"active",state_version:kn(r),verification_result:"pending",verification_report:null,verification:null,acceptance:r.acceptance.map(i=>i.result==="failed"||i.result==="blocked"?{...i,result:"pending",reason:null}:i),blockers:[],loop:{...r.loop,stage:"verify-ready",retry_epoch:r.loop.retry_epoch+1,execution_failure_count:0,next_action:"dispatch-new-verifier"}})}function ZN(e){let t=M(e.state);if(t.phase!=="verify"||t.status!=="active"||t.loop.attempt<1||t.loop.next_action!=="await-verifier-result")throw new Error("Native Verifier execution error requires an active Verify attempt");let r=(e.now??new Date).toISOString(),n=t.loop.execution_failure_count+1,i=n>=O8,o=vn(t,Il({state:t,outcome:"execution-error",summary:e.summary,completedAt:r}));return M({...o,status:i?"blocked":"active",state_version:kn(t),blockers:i?[{owner:"runtime",reason:cn(e.summary),acceptance_ids:[],resolution_action:"retry-verifier"}]:[],loop:{...t.loop,stage:i?"blocked":"verify-ready",execution_failure_count:n,next_action:i?"retry-verifier":"dispatch-new-verifier"}})}function eS(e){let t=M(e),r=t.status==="blocked"&&t.blockers.some(({resolution_action:s})=>s==="retry-verifier"),n=t.status==="await-user"&&t.verification_result==="blocked"&&t.verification?.assurance==="semantic-verification-unavailable"&&t.loop.stage==="await-user"&&t.loop.next_action==="confirm-verifier-unavailable"&&t.blockers.some(({resolution_action:s})=>s==="confirm-verifier-unavailable"),i=t.status==="await-user"&&t.verification_result==="pass"&&t.loop.next_action==="confirm-skill-coordinated-pass";if(t.phase!=="verify"||!r&&!n&&!i)throw new Error("Native change is not blocked on Verifier infrastructure");let o=_B(t),a=t.acceptance.some(({result:s})=>s==="passed");return M({...t,status:"active",state_version:kn(t),...n||i?{verification_result:"pending",verification_report:null,verification:null,...i?{acceptance:t.acceptance.map(s=>({...s,result:"pending",reason:null}))}:{}}:{},blockers:[],loop:{...t.loop,stage:"verify-ready",retry_epoch:t.loop.retry_epoch+1,execution_failure_count:0,...n?{previous_unresolved_ids:a?o:[]}:{},next_action:"dispatch-new-verifier"}})}function xl(e){let t=M(e.state);if(t.phase!=="verify"&&t.phase!=="archive")throw new Error("Only Verify or Archive can return a candidate to Build");let r=e.failureBudget,n=r?t.loop.failed_iteration_count+1:t.loop.failed_iteration_count,i=r!==void 0&&n>=r.maxVerifyFailures,o=(e.now??new Date).toISOString(),a=vn(t,Il({state:t,outcome:"recovery",summary:e.reason,completedAt:o})),s=new Set(t.loop.previous_unresolved_ids),c=s.size===0?CB(t.acceptance):t.acceptance.map(l=>s.has(l.id)?{...l,result:"pending",reason:null}:l);return i?M({...a,phase:"verify",status:"await-user",state_version:kn(t),verification_result:"fail",builder_handoff:t.builder_handoff,blockers:[{owner:"user",reason:cn(`Native Runtime checks failed at Builder handoff and reached the configured failed iteration limit: ${e.reason}`),acceptance_ids:[...s],resolution_action:"await-user"}],loop:{...t.loop,stage:"await-user",failed_iteration_count:n,execution_failure_count:0,stop_reason:"budget",next_action:"resolve-loop-stop"}}):M({...a,phase:"build",status:"active",state_version:kn(t),verification_result:"pending",verification_report:null,verification:null,builder_handoff:t.builder_handoff,blockers:[],acceptance:c,loop:{...t.loop,stage:"repairing",iteration:t.loop.iteration+1,attempt:0,execution_failure_count:0,failed_iteration_count:n,stop_reason:void 0,next_action:"submit-builder-candidate"}})}var O8,Vs=x(()=>{"use strict";Sm();Se();io();vs();Wd();UN();O8=3});import IB from"node:path";async function tS(e){let{paths:t,state:r}=e;if(r.phase!=="shape"||r.status!=="active")return;let n=IB.join(t.changesDir,r.name);for(let i of e.specChanges){if(i.operation!=="modify"||!i.delta_source||!i.source)continue;let o=await Pe({root:t.specsDir,ref:i.capability+"/spec.md",maxBytes:null,includeHash:!1}),a=await Pe({root:n,ref:i.delta_source,maxBytes:null,includeHash:!1}),s=nn(a.text);if(s.capability!==i.capability)throw new Error("Native Delta capability does not match its target");let c=Kj({baselineMarkdown:o.text,delta:s,allowAlreadyApplied:!0}),l=await Pe({root:n,ref:i.source,maxBytes:null,includeHash:!1});if(l.text!==c.markdown){if(l.text!==o.text)throw new Error("Native target has independent edits: "+i.source+". Reconcile the target and Delta before preparing Shape.");await qe(IB.join(n,...i.source.split("/")),c.markdown,{containedRoot:t.nativeRoot})}}}var rS=x(()=>{"use strict";dt();Er();il()});import{promises as B8}from"node:fs";function xB(e){if(!e.builder_handoff||!e.verification)throw new Error("Native verification result requires a candidate and accepted evidence");return of("comet.native.verification-result.v1",{candidateId:e.builder_handoff.candidate_id,acceptance:e.acceptance,verification:e.verification})}function bn(e){return e===null?"—":`${e.text.replace(/\r\n?/gu,`
|
|
328
|
+
`).replace(/\s+/gu," ").trim()||"—"}${e.truncated?" … (truncated)":""}`}function vi(e){return e.replaceAll("|","\\|").replace(/\r?\n/gu,"<br>")}function W8(e){return e.archived?on(e.language,"Archived","已归档"):e.phase==="verify"&&e.loop.next_action==="confirm-skill-coordinated-pass"?on(e.language,"Verification passed; your confirmation is required","验收通过,需要你确认"):e.phase==="archive"&&e.loop.next_action==="archive"?on(e.language,"Verification passed; ready to archive","验收通过,可归档"):on(e.language,"Verification passed","验收通过")}function q8(e){let t=e.language;return e.verification?.assurance==="semantic-verification-unavailable"?on(t,"Full verification was unavailable; only automatic checks completed","无法完成完整验证,只完成了自动检查"):e.verification_result==="pass"?W8(e):e.verification_result==="blocked"?on(t,"Blocked","已阻塞"):e.verification_result==="fail"?on(t,"Failed","未通过"):on(t,"Pending","待处理")}function L8(e){if(e.verification?.assurance==="semantic-verification-unavailable")return on(e.language,"Full verification was unavailable; only automatic checks completed","无法完成完整验证,只完成了自动检查");if(e.verification_result==="fail")return on(e.language,"Fix unresolved acceptance criteria and verify again","修复未通过的验收项后重新验证");if(e.verification_result==="blocked")return on(e.language,"Resolve the reported blockers and resume verification","解决报告中的阻塞项后恢复验证");let t=e.verification?.assurance??(e.builder_handoff?.identity_provider===$r?$r:"host-attested"),r=t===$r&&(e.archived||e.phase==="archive"&&e.loop.next_action==="archive");return(e.language==="en"?{"host-attested":"Host independently verified","self-reviewed":"Acceptance reviewed in the implementation session","skill-coordinated":r?"Checks completed; result confirmed":"Checks completed, but your confirmation is required","semantic-verification-unavailable":"Full verification was unavailable; only automatic checks completed","user-confirmed-degraded":"You accepted the incomplete verification result"}:{"host-attested":"已完成独立验证","self-reviewed":"已在实现会话中完成验收","skill-coordinated":r?"已完成检查,验证结果已确认":"已完成检查,但需要你确认验证结果","semantic-verification-unavailable":"无法完成完整验证,只完成了自动检查","user-confirmed-degraded":"你已确认接受不完整验证结果"})[t]??t}function $f(e,t){if(e.verification===null)throw new Error("Native verification report requires a stable Verifier result");let r=e.language,n=d=>N0(r,d),i=(d,p)=>on(r,d,p),o=e.acceptance.map(d=>`| ${vi(d.id)} | ${vi(d.result)} | ${vi(d.source)} | ${vi(d.text)} | ${vi(bn(d.reason))} |`).join(`
|
|
329
|
+
`),a=e.verification.reported_checks?[`| ${i("Agent-reported check","Agent 报告的检查")} | ${i("Result","结果")} | ${i("Execution and evidence","执行与证据")} |`,"| --- | --- | --- |",...e.verification.reported_checks.map(d=>`| ${vi(bn(d.name))} | ${d.result} | ${vi(bn(d.note))} |`)].join(`
|
|
330
|
+
`):e.verification.checks.length===0?`_${i("No Runtime checks were recorded.","没有记录 Runtime 检查。")}_`:[`| ${i("Check","检查")} | ${i("Command","命令")} | ${i("Working directory","工作目录")} | ${i("Status","状态")} | ${i("Exit","退出码")} | ${i("Duration","耗时")} |`,"| --- | --- | --- | --- | ---: | ---: |",...e.verification.checks.map(d=>{let p=d.argv_display.map(bn).join(" ");return`| ${vi(bn(d.name))} | ${vi(p||"—")} | ${vi(d.cwd_ref)} | ${d.status} | ${d.exit_code??"—"} | ${d.duration_ms} ms |`})].join(`
|
|
331
|
+
`),s=e.builder_handoff?[`### ${i("Builder-reported evidence","Builder 报告的证据")}`,"",i("These are Builder reports, not Runtime check receipts or independent verification results.","以下为 Builder 报告,不等同于 Runtime 检查凭据或独立验收结果。"),"",...e.builder_handoff.checks.map(d=>`- ${bn(d.name)}: ${d.result} — ${bn(d.note)}`),...e.builder_handoff.checks_truncated?[i("Check list was truncated.","检查列表已截断。")]:[],...e.builder_handoff.known_limits.map(d=>`- ${i("Known limitation","已知限制")}: ${bn(d)}`),...e.builder_handoff.known_limits_truncated?[i("Limitations list was truncated.","限制列表已截断。")]:[]].join(`
|
|
332
|
+
`):"",c=e.blockers.length===0?`_${i("None.","无。")}_`:e.blockers.map(d=>`- **${d.owner}**: ${bn(d.reason)}${d.acceptance_ids.length>0?` (acceptance: ${d.acceptance_ids.join(", ")})`:""} — next: \`${d.resolution_action}\``).join(`
|
|
333
|
+
`),l=e.verification.risks.length===0?`_${i("None reported.","未报告风险。")}_`:e.verification.risks.map(d=>`- ${bn(d)}`).join(`
|
|
334
|
+
`),u=e.history.length===0?`_${i("No previous iterations.","没有之前的迭代。")}_`:[`| ${i("Goal cycle","目标周期")} | ${i("Iteration","迭代")} | ${i("Attempt","尝试")} | ${i("Outcome","结果")} | ${i("Unresolved","未解决项")} | ${i("Summary","摘要")} | ${i("Completed","完成时间")} |`,"| ---: | ---: | ---: | --- | --- | --- | --- |",...e.history.map(d=>`| ${d.goal_cycle} | ${d.iteration} | ${d.attempt} | ${d.outcome} | ${d.unresolved_ids.join(", ")||"—"} | ${vi(bn(d.summary))} | ${d.completed_at} |`)].join(`
|
|
335
|
+
`),f=t?.finalVerification.layers?`
|
|
336
|
+
## ${i("Supervisor evidence layers","Supervisor 分层证据")}
|
|
337
|
+
|
|
338
|
+
- ${i("Child verification","Child 验证")}: ${t.finalVerification.layers.childVerification}
|
|
339
|
+
- ${i("Parent integration","父级集成")}: ${t.finalVerification.layers.parentIntegration}
|
|
340
|
+
- ${i("Parent checks","父级检查")}: ${t.finalVerification.layers.parentChecks.join(", ")||"—"}
|
|
341
|
+
- ${i("Not rerun","未重跑")}: ${t.finalVerification.layers.notRerun.join(", ")||"—"}
|
|
342
|
+
- ${i("Incomplete","未完成")}: ${t.finalVerification.layers.incomplete.join(", ")||"—"}
|
|
343
|
+
`:"";return`---
|
|
344
|
+
generated_from_state_version: ${e.state_version}
|
|
345
|
+
---
|
|
346
|
+
|
|
347
|
+
# ${n("verification")}
|
|
348
|
+
|
|
349
|
+
## ${n("currentResult")}
|
|
350
|
+
|
|
351
|
+
- ${i("Result","结果")}: **${q8(e)}**
|
|
352
|
+
- ${i("Verification status","验证情况")}: **${L8(e)}**
|
|
353
|
+
- ${i("Goal cycle","目标周期")}: ${e.loop.goal_cycle}
|
|
354
|
+
- ${i("Iteration","迭代")}: ${e.verification.iteration}
|
|
355
|
+
- ${i("Verifier attempt","验证器尝试次数")}: ${e.verification.attempt}
|
|
356
|
+
- ${i("Completed","完成时间")}: ${e.verification.completed_at}
|
|
357
|
+
- ${i("Summary","摘要")}: ${bn(e.verification.summary)}
|
|
358
|
+
|
|
359
|
+
## ${n("acceptance")}
|
|
360
|
+
|
|
361
|
+
| ${i("ID","编号")} | ${i("Result","结果")} | ${i("Source","来源")} | ${i("Criterion","验收项")} | ${i("Reason","原因")} |
|
|
362
|
+
| --- | --- | --- | --- | --- |
|
|
363
|
+
${o}
|
|
364
|
+
|
|
365
|
+
## ${n("checks")}
|
|
366
|
+
|
|
367
|
+
${a}
|
|
368
|
+
|
|
369
|
+
${s}
|
|
370
|
+
|
|
371
|
+
## ${n("blockers")}
|
|
372
|
+
|
|
373
|
+
${c}
|
|
374
|
+
|
|
375
|
+
## ${n("risks")}
|
|
376
|
+
|
|
377
|
+
${l}
|
|
378
|
+
|
|
379
|
+
## ${n("previousIterations")}
|
|
380
|
+
|
|
381
|
+
${u}
|
|
382
|
+
|
|
383
|
+
${f}
|
|
384
|
+
|
|
385
|
+
${e.history_overflow.dropped_entries>0?`${i("Earlier history entries folded into summary","更早的历史记录已折叠到摘要中")}: ${e.history_overflow.dropped_entries}.
|
|
386
|
+
|
|
387
|
+
`:""}## ${n("conclusion")}
|
|
388
|
+
|
|
389
|
+
${bn(e.verification.summary)}
|
|
390
|
+
`}function V8(e){let t=/^---\r?\ngenerated_from_state_version: ([1-9]\d*)\r?\n---(?:\r?\n|$)/u.exec(e);if(!t)return null;let r=Number(t[1]);return Number.isSafeInteger(r)?r:null}async function Df(e){let t;try{t=await B8.readFile(e.file,"utf8")}catch(n){if(n.code==="ENOENT")return"missing";throw n}let r=V8(t);return r===null?"invalid":r===e.stateVersion?"aligned":"stale"}async function nv(e){await qe(e.file,$f(e.state,e.supervisor),{beforeCommit:e.beforeCommit})}var Pl=x(()=>{"use strict";Se();ul();dt();sg();vs()});import{randomUUID as M8}from"node:crypto";import{promises as F8}from"node:fs";import Bf from"node:path";function Ms(e){return"native/preserved-verification/"+encodeURIComponent(e)}function iv(e,t){if(!e.builder_handoff||!e.verification)throw new Error("Native report requires its accepted Verifier result");return{candidateId:e.builder_handoff.candidate_id,reportRef:Bf.posix.join(t.replaceAll("\\","/"),"comet","changes",e.name,"verification.md"),stateVersion:e.state_version,iteration:e.loop.iteration,attempt:e.loop.attempt}}async function Wf(e){let{state:t,paths:r,file:n}=e,i=Bf.relative(r.projectRoot,n).replaceAll("\\","/"),o=await Qe(r.projectRoot,i,Number.MAX_SAFE_INTEGER,{label:"Native verification view"}).catch(c=>{if(c.code==="ENOENT")return null;throw c}),a=$f(t);if(o?.bytes.equals(Buffer.from(a)))return{};let s;if(o){await Cn(r.projectRoot);let c=Ms(e.runId);await $t(r.workspaceRuntimeRoot,c,{label:"Native preserved report"}),s=c+"/"+M8()+".md",await F8.writeFile(Bf.join(r.workspaceRuntimeRoot,...s.split("/")),o.bytes,{flag:"wx"})}return await qe(n,a,{containedRoot:r.projectRoot}),s?{preservedReportRef:s}:{}}async function PB(e,t){if(!M(t.state).archived)return;let n=await we(e,t.input.artifactRootRef,{readOnly:!0}),i=t.outputs["archive.finalize"]?.value;if(!i?.archiveRef)return;let o=Bf.relative(e,Bf.join(n.archiveDir,i.archiveRef,"verification.md")).replaceAll("\\","/"),a=!1;try{a=(await ie(e,o,{label:"Native archived verification view",expected:"file"})).exists}catch{}return a?void 0:{code:"NATIVE_REPORT_PENDING",message:"归档已完成,验证报告阅读视图尚不可用;实际验收结果和归档进度已保存。",reportRef:o}}var Co=x(()=>{"use strict";lt();or();dt();He();Se();Pl()});import{promises as ov}from"node:fs";import av from"node:path";function TB(e,t){let r=e.map(({code:n,message:i,path:o})=>`- ${n}${o?` (${o})`:""}: ${i}`).join(`
|
|
391
|
+
`);return[`Native ${t.phase} document checks failed for ${t.change}.`,r,"Recovery: edit the reported formal file in the configured Native change directory, then rerun the latest continuation command. The current state and existing work are preserved; do not edit comet-state.yaml or bypass the Hook."].join(`
|
|
392
|
+
`)}async function sv(e){let t=Mt(e.paths,e.state.name),r=e.state.document_constraints_version,n=r===2||r===3,i=r===3,o=[...(await vB(t,e.state.brief,{strict:!0,compact:n,structure:i,maxBytes:null})).findings],a=e.specChanges??e.state.spec_changes,s=a.filter(({operation:d})=>d!=="remove"),c=e.state.spec_changes.filter(({operation:d})=>d!=="remove"),l=new Set(s.map(({capability:d})=>d)),u=e.state.phase==="shape",f=new Set(a.filter(({operation:d})=>d==="remove").map(({capability:d})=>d));if(e.specChanges!==void 0&&!(u&&s.length>0))for(let d of c)l.has(d.capability)||u&&f.has(d.capability)||o.push({code:"spec-document-missing",message:u?`Previously declared target Spec is missing: specs/${d.capability}/spec.md. Restore the complete file, stage the replacement target Spec under specs/<capability>/spec.md, or record the intended capability deletion as a formal remove entry.`:`Previously declared target Spec is missing: specs/${d.capability}/spec.md. Restore the complete file or record the intended capability deletion as a formal remove entry.`,path:`specs/${d.capability}/spec.md`});for(let d of s){let p=`specs/${d.capability}/spec.md`;if(d.source!==p){o.push({code:"spec-source-path-invalid",message:`Target Spec must be staged at ${p}.`,path:d.source??p});continue}try{let m=(await Pe({root:t,ref:p,maxBytes:null,includeHash:!1})).text;o.push(...gB(m,p).findings)}catch(m){o.push({code:"spec-document-missing",message:`Target Spec cannot be read: ${m.message}. Restore the complete file at ${p}.`,path:p})}}return{valid:o.length===0,findings:o}}async function nS(e){let t=await sv(e);if(!t.valid)throw new Cl(TB(t.findings,{change:e.state.name,phase:e.state.phase}),t.findings,e.state.name)}async function cv(e){let t=Mt(e.paths,e.state.name),r=av.join(t,"specs"),n=new Map(e.state.spec_changes.filter(({operation:a})=>a==="remove").map(a=>[a.capability,a])),i;try{i=await ov.readdir(r,{withFileTypes:!0})}catch(a){if(a.code==="ENOENT")i=[];else throw a}let o=[];for(let a of i.sort((s,c)=>s.name.localeCompare(c.name,"en"))){if(a.isSymbolicLink())throw new Error(`Native spec capability is unsafe: ${a.name}`);if(!a.isDirectory())continue;if(!Rg.test(a.name))throw new Error(`Invalid Native capability: ${a.name}`);if(n.has(a.name))throw new Error(`Capability ${a.name} cannot be proposed and removed together`);let s=`specs/${a.name}/spec.md`,c=av.join(t,...s.split("/")),l=await ov.lstat(c);if(!l.isFile()||l.isSymbolicLink())throw new Error(`Native proposed spec must be a regular file: ${s}`);let u=av.join(e.paths.specsDir,a.name,"spec.md"),f="create";try{let h=await ov.lstat(u);if(!h.isFile()||h.isSymbolicLink())throw new Error(`Canonical Native spec is unsafe: ${a.name}`);f="modify"}catch(h){if(h.code!=="ENOENT")throw h}let d=`specs/${a.name}/${Fj}`,p=av.join(t,...d.split("/")),m={};try{let h=await ov.lstat(p);if(!h.isFile()||h.isSymbolicLink())throw new Error(`Native delta manifest must be a regular file: ${d}`);let g=await Pe({root:t,ref:d,maxBytes:null,includeHash:!1}),v=nn(g.text);if(v.capability!==a.name)throw new Error(`Native delta capability ${v.capability} does not match directory ${a.name}`);m={delta_source:d}}catch(h){if(h.code!=="ENOENT")throw h}o.push({capability:a.name,operation:f,source:s,...m})}return o.push(...n.values()),o.sort((a,s)=>a.capability.localeCompare(s.capability,"en"))}async function lv(e){let t=Mt(e.paths,e.state.name),r=async o=>{let a=e.artifactTexts?.get(o);return a!==void 0?a:(await Pe({root:t,ref:o,maxBytes:null,includeHash:!1})).text},n=await r("brief.md"),i=[];for(let o of e.specChanges)o.source!==null&&i.push({capability:o.capability,source:o.source,markdown:await r(o.source)});return{acceptance:lg({briefMarkdown:n,specs:i,legacyBriefBoundaries:e.legacyBriefBoundaries,resolveBriefReferences:e.state.document_constraints_version!==void 0&&e.state.document_constraints_version!==1})}}var J8,Sa=x(()=>{"use strict";lr();ul();tv();dt();Er();Hi();bo();Et();il();Vs();St();He();sf();Se();Ft();io();rS();Oi();Co();J8=nf("en",{compact:!0})});var OB=x(()=>{"use strict";bo();Ft()});var $B=x(()=>{"use strict";it();bo();Et();Vs();St();Sa();Se();Ft();io();mf();ai();Oi();rn()});var uv=x(()=>{"use strict";Se();io();Ft()});var DB=x(()=>{"use strict";mf();Oi();Vs();St();Sa();Ft();vs();Pl();Co();Td();Wd()});var WB=x(()=>{"use strict";Vs();St();Sa();Ft();uv();mf();Oi();Co()});var qB=x(()=>{"use strict";dt();Er();bo();il();St();sf();Sa();Ft();uv()});var LB=x(()=>{"use strict";OB();Sa();$B();Ft();uv();DB();WB();qB()});async function K8(e){let t=await an(e.projectRoot);if(t.status==="missing")return null;if(t.selection.workflow!=="native"){if(t.selection.workflow!=="application")return null;let r=await Fe(e.projectRoot,"native",t.selection.change,{readOnly:!0});if(!r||r.application!==t.selection.applicationId)return null}return sl(t.selection.change),t.selection}function iS(e){return yf(e.projectRoot)}async function oS(e,t){await Nc(e.projectRoot);let r=await K8(e);return r?.change===t?js(e.projectRoot,r.workflow,t):!1}var Sve,dv=x(()=>{"use strict";wa();lr();Hi();Et();St();Se();LB();ze();Rl();Sve=Number.MAX_SAFE_INTEGER});import{createHash as G8,randomUUID as Y8}from"node:crypto";import{promises as Tt}from"node:fs";import An from"node:path";function aS(e){return`${(e.verification?.completed_at??e.created_at).slice(0,10)}-${e.name}`}function Ol(e,t){if(!/^\d{4}-\d{2}-\d{2}-[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(t))throw new Error("Native portable Archive ref is invalid");let r=An.join(e.archiveDir,t);if(!yt(e.archiveDir,r))throw new Error("Native Archive path escaped");return r}async function Ji(e){try{return await Tt.lstat(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function Lf(e,t){let r=await Mn(e,{kind:"archive",change:t});return r?.kind==="archive"?r.journal:null}async function qf(e,t){await Tt.mkdir(e.transactionsDir,{recursive:!0}),await Bt(Ss(e,{kind:"archive",change:t.change}),t,{containedRoot:e.runtimeDir})}async function cS(e,t){let r=An.join(e.specsDir,t),n=An.join(r,"spec.md");if(!yt(e.specsDir,n))throw new Error("Native canonical spec path escaped");let i;try{i=await Tt.lstat(e.specsDir)}catch(l){if(l.code==="ENOENT")return{text:"",exists:!1};throw l}if(!i.isDirectory()||i.isSymbolicLink())throw new Error("Native canonical specs root is unsafe");let o;try{o=await Tt.lstat(r)}catch(l){if(l.code==="ENOENT")return{text:"",exists:!1};throw l}if(!o.isDirectory()||o.isSymbolicLink())throw new Error(`Canonical Native capability directory is unsafe: ${t}`);let[a,s]=await Promise.all([Tt.realpath(e.specsDir),Tt.realpath(r)]);if(!yt(a,s))throw new Error(`Canonical Native capability directory is unsafe: ${t}`);let c;try{c=await Tt.lstat(n)}catch(l){if(l.code==="ENOENT")return{text:"",exists:!1};throw l}if(!c.isFile()||c.isSymbolicLink())throw new Error(`Canonical Native spec is unsafe: ${t}`);if(!yt(s,await Tt.realpath(n)))throw new Error(`Canonical Native spec is unsafe: ${t}`);try{return{text:(await Pe({root:e.specsDir,ref:`${t}/spec.md`,maxBytes:null,includeHash:!1})).text,exists:!0}}catch(l){if(l.code==="ENOENT")return{text:"",exists:!1};throw l}}async function X8(e){let t=An.join(e.paths.specsDir,e.change.capability),r=An.join(t,"spec.md");if(!yt(e.paths.specsDir,r))throw new Error("Native canonical spec path escaped");if(e.change.operation==="remove"){let s;try{s=await Tt.lstat(e.paths.specsDir)}catch(f){if(f.code==="ENOENT")return;throw f}if(!s.isDirectory()||s.isSymbolicLink())throw new Error("Native canonical specs root is unsafe");let c;try{c=await Tt.lstat(t)}catch(f){if(f.code==="ENOENT")return;throw f}if(!c.isDirectory()||c.isSymbolicLink())throw new Error(`Canonical Native capability directory is unsafe: ${e.change.capability}`);let[l,u]=await Promise.all([Tt.realpath(e.paths.specsDir),Tt.realpath(t)]);if(!yt(l,u))throw new Error("Native canonical capability path escaped");try{let f=await Tt.lstat(r);if(!f.isFile()||f.isSymbolicLink())throw new Error(`Canonical Native spec is unsafe: ${e.change.capability}`);await Tt.unlink(r)}catch(f){if(f.code!=="ENOENT")throw f}await Tt.rmdir(t).catch(f=>{if(f.code!=="ENOENT"&&f.code!=="ENOTEMPTY")throw f});return}if(e.change.source===null||e.change.content===null)throw new Error(`Native ${e.change.operation} spec requires frozen source content`);let n=await cS(e.paths,e.change.capability),i=e.change.delta_content?Ud({currentMarkdown:n.text,delta:nn(e.change.delta_content)}).markdown:e.change.content,o=n.exists&&n.text===i;if(e.change.operation==="create"&&n.exists&&!o)throw new Error(`Canonical Native spec conflicts with the pending create: ${e.change.capability}`);let a=An.join(Mt(e.paths,e.state.name),e.change.source);await qe(a,e.change.source_content??e.change.content,{containedRoot:e.paths.nativeRoot}),!o&&(await Tt.mkdir(t,{recursive:!0}),await qe(r,i,{containedRoot:e.paths.nativeRoot}))}function lS(e){if(e.phase!=="archive"||e.status!=="active"||e.loop.stage!=="archive-ready"||e.verification_result!=="pass"||e.verification?.verdict!=="pass"||e.verification_report!=="verification.md")throw new Error(`Native change ${e.name} is not archive-ready`)}async function Z8(e,t){let r=Mt(e,t.name),n=[];for(let i of t.spec_changes){if(i.source===null){n.push({...i,content:null});continue}let o=await Pe({root:r,ref:i.source,maxBytes:null,includeHash:!1});if(i.delta_source){let a=await Pe({root:r,ref:i.delta_source,maxBytes:null,includeHash:!1}),s=nn(a.text);if(s.capability!==i.capability)throw new Error(`Native delta capability ${s.capability} does not match ${i.capability}`);let c=await cS(e,i.capability),l=Ud({currentMarkdown:c.text,delta:s});n.push({...i,content:l.markdown,delta_content:a.text,source_content:o.text});continue}n.push({...i,content:o.text})}return n}function uS(e,t){if(t.archived){if(t.status!=="done"||t.loop.stage!=="done"||t.state_version!==e.start_state_version+1)throw new Error("Native Archive transaction no longer matches the finalized portable state");return}if(t.state_version!==e.start_state_version)throw new Error("Native Archive transaction is stale for the current portable state");if(lS(t),e.status!=="prepared"&&e.status!=="specs-applied")throw new Error(`Native Archive transaction ${e.status} requires a finalized portable state`)}async function e5(e){let t=[],r=[];for(let n of e.state.spec_changes)try{let i=Mt(e.paths,e.state.name);n.source&&await Pe({root:i,ref:n.source,maxBytes:null,includeHash:!1});let o;if(n.delta_source){let a=await Pe({root:i,ref:n.delta_source,maxBytes:null,includeHash:!1}),s=nn(a.text);if(s.capability!==n.capability)throw new Error("Native delta capability does not match its target");let c=await cS(e.paths,n.capability);o=[...Ud({currentMarkdown:c.text,delta:s}).operationResults]}r.push({capability:n.capability,operation:n.operation,source:n.source,...n.delta_source?{delta_source:n.delta_source,delta_operations:o}:{}})}catch(i){t.push(i.message)}return{blockers:t,requiresReverification:!1,specPreview:r}}async function dS(e){let t=e.state??await wn(e.paths,e.name);if(t.name!==e.name)throw new Error("Native Archive state belongs to another change");let r=[];if(e.state===void 0)try{let s=await Lj(e.paths,t);s&&!rl(s)&&Hd(s)}catch(s){r.push(s.message)}let n=!1,i;if(t.document_constraints_version===1){let s=await sv({paths:e.paths,state:t});r.push(...s.findings.map(({message:c})=>c))}try{lS(t)}catch(s){r.push(s.message)}let o=await Lf(e.paths,e.name);if(o===null){let s=Ol(e.paths,aS(t));await Ji(s)&&r.push(`Native Archive target already exists: ${s}`);let c=await e5({paths:e.paths,state:t});r.push(...c.blockers),n=c.requiresReverification,i=c.specPreview}else i=o.spec_changes.map(s=>({capability:s.capability,operation:s.operation,source:s.source,...s.delta_source===void 0?{}:{delta_source:s.delta_source},...s.delta_content?{delta_operations:nn(s.delta_content).operations.map(c=>({id:c.id,operation:c.operation,status:"changed",targetIds:c.operation==="rename"?[c.id,c.to_id]:[c.id]}))}:{}}));let a=e.derivedReport?"aligned":t.verification===null?"missing":await Df({file:An.join(Mt(e.paths,t.name),"verification.md"),stateVersion:e.verificationReportStateVersion??t.state_version});return a!=="aligned"&&r.push(`verification.md is ${a}`),{ready:r.length===0,blockers:r,requiresReverification:n,specPreview:i,capabilityPeers:[],archiveDir:Ol(e.paths,aS(t)),stateVersion:t.state_version}}async function VB(e){let{paths:t,state:r}=e;return $e(t,async()=>{lS(r);let n=await Lf(t,r.name);if(n)uS(n,r);else{let i=await dS({paths:t,name:r.name,state:r,verificationReportStateVersion:e.verificationReportStateVersion,derivedReport:e.derivedReport});if(!i.ready)throw new Error(`Native SDK Archive preflight is blocked: ${i.blockers.join("; ")}`);n={schema:dg,id:Y8(),change:r.name,start_state_version:r.state_version,archive_ref:aS(r),status:"prepared",next_spec_index:0,spec_changes:await Z8(t,r),created_at:new Date().toISOString()},await qf(t,n)}if(n.status==="prepared"){for(let i=n.next_spec_index;i<n.spec_changes.length;i+=1)await X8({paths:t,state:r,change:n.spec_changes[i]}),n={...n,next_spec_index:i+1},await qf(t,n);n={...n,status:"specs-applied"},await qf(t,n)}return n},{allowedPortableTransaction:{kind:"archive",change:r.name}})}async function fS(e){let t=await Lf(e.paths,e.state.name);if(!t||t.status!=="specs-applied")throw new Error("Native SDK Archive Specs have not been applied");if(uS(t,e.state),t.next_spec_index!==t.spec_changes.length)throw new Error("Native SDK Archive Spec transaction is incomplete");return{transactionId:t.id,archiveRef:t.archive_ref,stateVersion:t.start_state_version,specCount:t.spec_changes.length}}async function t5(e,t,r){let n=An.join(Ol(e,t),"comet-state.yaml"),i;try{i=await Tt.readFile(n,"utf8")}catch(a){if(a.code==="ENOENT")return;throw a}if(!ms(i))return;let o=(0,sS.parseDocument)(i,{uniqueKeys:!0});if(o.errors.length>0)throw new Error("Native SDK Archive state is invalid");o.set(MB,r),await qe(n,o.toString(),{containedRoot:e.nativeRoot})}async function r5(e,t){let r=An.join(Ol(e,t),"comet-state.yaml"),n=await Pe({root:e.nativeRoot,ref:An.relative(e.nativeRoot,r).replaceAll("\\","/"),maxBytes:null});if(!ms(n.text))throw new Error("Native SDK Archive portable receipt has no managed Run");let i=(0,sS.parseDocument)(n.text,{uniqueKeys:!0});if(i.errors.length>0)throw new Error("Native SDK Archive state is invalid");return i.toJS()[MB]}function FB(e,t){if(!t.trim())throw new Error("Native SDK Archive Run ID is missing");let r=G8("sha256").update(t).digest("hex");return An.join(e.runtimeDir,"sdk-archive-receipts",`${r}.json`)}async function pS(e){let{paths:t,state:r,runId:n}=e;return $e(t,async()=>{if(r.phase!=="archive"||r.status!=="done"||!r.archived||r.loop.stage!=="done")throw new Error("Native SDK Archive finalization requires committed done state");let i=await Lf(t,r.name);if(!i){let l=await jl({paths:t,state:r,runId:n,archiveRef:e.archiveRef});if(l.transactionId!==e.transactionId)throw new Error("Native Archive recovery belongs to another transaction");return l}if(uS(i,r),i.id!==e.transactionId||i.archive_ref!==e.archiveRef||i.next_spec_index!==i.spec_changes.length||i.spec_changes.length!==r.spec_changes.length||i.spec_changes.some((l,u)=>l.capability!==r.spec_changes[u]?.capability||l.operation!==r.spec_changes[u]?.operation||l.source!==r.spec_changes[u]?.source)||!["specs-applied","report-aligned","moved"].includes(i.status))throw new Error("Native SDK Archive recovery does not match its completed Spec operations");let o=Mt(t,r.name),a=Ol(t,i.archive_ref);if(i.status==="specs-applied"){if(!await Ji(o)||await Ji(a))throw new Error("Native Archive layout contradicts its transaction");let l=An.join(o,"verification.md");if(!await Ji(l))try{e.derivedReport?await e.derivedReport.write(l):await nv({file:l,state:r})}catch(u){if(!e.derivedReport?.optionalView)throw u}i={...i,status:"report-aligned"},await qf(t,i)}if(i.status==="report-aligned"){let l=await Ji(o),u=await Ji(a);if(l===u)throw new Error("Native Archive layout contradicts its transaction");l&&(await Tt.mkdir(t.archiveDir,{recursive:!0}),await ro(o,a)),i={...i,status:"moved"},await qf(t,i)}if(i.status!=="moved"||await Ji(o)||!await Ji(a))throw new Error("Native SDK Archive has not moved the change");let s={runId:n,change:r.name,archiveRef:i.archive_ref,transactionId:i.id,stateVersion:r.state_version,specs:i.spec_changes.map(l=>({capability:l.capability,operation:l.operation}))};await t5(t,i.archive_ref,s);let c=FB(t,n);return await Tt.mkdir(An.dirname(c),{recursive:!0}),await Bt(c,s,{containedRoot:t.runtimeDir}),await Tt.rm(Ss(t,{kind:"archive",change:r.name}),{force:!0}),s},{allowedPortableTransaction:{kind:"archive",change:r.name}})}async function jl(e){let{paths:t,state:r,runId:n}=e,i;try{i=JSON.parse(await Tt.readFile(FB(t,n),"utf8"))}catch(o){if(o.code!=="ENOENT"||!e.archiveRef)throw o;i=await r5(t,e.archiveRef)}if(!i||i.runId!==n||i.change!==r.name||i.stateVersion!==r.state_version||e.archiveRef!==void 0&&i.archiveRef!==e.archiveRef||typeof i.transactionId!="string"||!Array.isArray(i.specs)||i.specs.length!==r.spec_changes.length||i.specs.some((o,a)=>o?.capability!==r.spec_changes[a]?.capability||o.operation!==void 0&&o.operation!==r.spec_changes[a]?.operation)||await Lf(t,r.name)||await Ji(Mt(t,r.name)))throw new Error("Native SDK Archive completion record does not match its Run or transaction");if(!await Ji(Ol(t,i.archiveRef)))throw new Error("Native SDK Archive destination is missing");return i}async function HB(e){let{projectRoot:t,store:r,runId:n,expectedRevision:i,next:o,actionId:a,state:s}=e,c=await we(t,o.input.artifactRootRef);return $e(c,async()=>{let l=await r.read(n);if(l?.revision!==i)return!1;if(l.actions.find(f=>f.id===a)?.status==="unknown"&&await Mn(c,{kind:"archive",change:s.name}))throw new Error("Native Archive has a transaction; recover its actual progress with archive --recover");return r.compareAndSwap(n,i,o)},{allowedPortableTransaction:{kind:"archive",change:s.name}})}var sS,MB,fv=x(()=>{"use strict";rn();Ft();dv();sS=dr(Ur(),1);Du();Qc();dt();Er();il();St();He();Sa();Ft();Se();Es();Pl();MB="archive_receipt"});import pv from"node:path";import{isDeepStrictEqual as n5}from"node:util";function QB(e){let t=e.actions.at(-1);return e.status==="failed"&&e.reason==="ACTION_FAILED: archive.prepare"&&t?.stepId==="archive.prepare"&&t.ref==="native-archive-preflight"&&t.type==="call_tool"&&t.status==="failed"&&t.retry==="idempotent"&&!t.rejectedOutcomes?.some(r=>r.outcome.attempt===t.attempt)&&!e.actions.some(r=>["running","unknown","pending"].includes(r.status))&&!e.waits.some(r=>r.status==="pending")&&!e.evidenceWaits?.some(r=>r.status==="pending")?t:void 0}function UB(e){let t=e.actions.at(-1);return e.status==="failed"&&t?.stepId==="archive.finalize"&&t.status==="failed"&&t.claim?.executorId===Vf.id&&t.outcome?.output?.reason==="candidate-drift"&&!t.rejectedOutcomes?.some(r=>r.outcome.attempt===t.attempt)&&!e.actions.some(r=>["running","unknown","pending"].includes(r.status))&&!e.waits.some(r=>r.status==="pending")&&!e.evidenceWaits?.some(r=>r.status==="pending")?t:void 0}async function i5(e,t,r){let n=M(e.state),i=e.input,o=e.waits.some(u=>u.stepId==="verify.confirm"&&u.status==="resolved"&&u.decision?.choice==="approved");if(n.phase!=="archive"||n.status!=="active"||n.loop.stage!=="archive-ready"||!n.builder_handoff||!n.verification||n.verification_result!=="pass"||i.name!==n.name||typeof i.artifactRootRef!="string"||t.stepId!=="archive.prepare"||t.ref!=="native-archive-preflight"||!o)throw new Error("Native Archive preflight lacks a confirmed SDK result");let a=await Te(r);if(!a||a.native.artifact_root!==i.artifactRootRef)throw new Error("Native artifact root changed after Run creation");let s=await we(r,i.artifactRootRef,{readOnly:!0}),c=pv.join(s.changesDir,n.name,"verification.md"),l=pv.relative(r,c).replaceAll("\\","/");return{state:n,paths:s,reportFile:c,reportRef:l,reportStateVersion:n.state_version-1}}async function o5(e,t,r){let n=await i5(e,t,r),i=await dS({paths:n.paths,name:n.state.name,state:n.state,requireCurrentAcceptance:!1,verificationReportStateVersion:n.reportStateVersion,derivedReport:!0}),o=pv.relative(r,i.archiveDir).replaceAll("\\","/");if(o.startsWith("../")||pv.isAbsolute(o))throw new Error("Native Archive destination is outside the project");return{candidateId:n.state.builder_handoff.candidate_id,stateVersion:n.state.state_version,reportRef:n.reportRef,reportStateVersion:n.reportStateVersion,archiveDirRef:o,ready:i.ready,blockers:i.blockers,requiresReverification:i.requiresReverification,capabilityPeers:i.capabilityPeers,specPreview:i.specPreview}}async function JB(e,t,r){return o5(e,t,r)}function zB(e,t,r){return JSON.stringify([r,e.runId,e.revision,t.id,t.attempt,t.claim?.token])}async function hS(e,t,r,n=!1){let i=M(e.state),o=e.input,a=e.outputs["archive.prepare"]?.value;if(i.phase!=="archive"||i.status!=="active"||!i.builder_handoff||o.name!==i.name||typeof o.artifactRootRef!="string"||t.stepId!=="archive.execute"||t.ref!=="native-archive"||!a||a.ready!==!0||a.candidateId!==i.builder_handoff.candidate_id||a.stateVersion!==i.state_version)throw new Error("Native SDK Archive apply lacks a successful preflight for its current step");let s=await Te(r);if(!s||s.native.artifact_root!==o.artifactRootRef)throw new Error("Native artifact root changed after Run creation");let c=await we(r,o.artifactRootRef,{readOnly:!0});if(n){let l=await Mn(c,{kind:"archive",change:i.name});if(l?.kind!=="archive"||l.journal.spec_changes.length!==i.spec_changes.length||l.journal.spec_changes.some((u,f)=>u.capability!==i.spec_changes[f]?.capability||u.operation!==i.spec_changes[f]?.operation))throw new Error("Native Archive recovery belongs to different Spec operations");await fS({paths:c,state:i})}return{state:i,paths:c,verificationReportStateVersion:a.reportStateVersion,derivedReport:!0}}function a5(e){if(e.status==="unknown")return e.rejectedOutcomes?.find(({outcome:t})=>{let r=t.output;return t.actionId===e.id&&t.attempt===e.attempt&&t.inputHash===e.inputHash&&t.claimToken===e.claim?.token&&t.outcomeId===`${e.id}:${e.attempt}:executor-result`&&t.status==="failed"&&t.event===void 0&&r!==null&&typeof r=="object"&&!Array.isArray(r)&&r.ready===!1&&r.reason==="candidate-drift"&&typeof r.message=="string"&&r.message.trim().length>0&&Object.keys(r).length===3})?.outcome.output}async function KB(e,t,r){let n=M(e.state),i=e.input,o=e.outputs["archive.execute"]?.value;if(n.phase!=="archive"||n.status!=="done"||!n.archived||i.name!==n.name||typeof i.artifactRootRef!="string"||t.stepId!=="archive.finalize"||t.ref!=="native-archive-finalize"||!o||o.stateVersion!==n.state_version-1||typeof o.transactionId!="string"||typeof o.archiveRef!="string")throw new Error("Native SDK Archive finalization lacks its completed Spec transaction");let a=await we(r,i.artifactRootRef,{readOnly:!0});return{state:n,paths:a,applied:o}}async function GB(e,t,r,n=!1){return KB(e,t,r)}function YB(e,t){return{optionalView:!0,preservedReportsRef:Ms(e.runId),write:r=>Wf({state:t.state,paths:t.paths,runId:e.runId,file:r})}}async function XB(e){let{run:t,projectRoot:r}=e,n=t.actions.at(-1),i=[...t.actions].reverse().find(u=>u.stepId==="archive.execute");if(t.status!=="cancelled"||n?.stepId!=="archive.finalize"||n.status!=="cancelled"||n.claim&&n.claim.executorId!==Vf.id||i?.status!=="succeeded"||!(await Rf({projectRoot:r,run:t,...e.readOnly?{}:{}})).quiescent)throw new Error("Cancelled Native Archive recovery requires applied Specs and proof that all original executions stopped");let o=t.input,a=await we(r,o.artifactRootRef,{readOnly:!0}),s=await Mn(a,{kind:"archive",change:M(t.state).name});if(s&&e.readOnly)throw new Error("取消归档仍有待收尾事务;只读诊断不能代替显式恢复");let c=await GB(t,n,r,s===null),l=s?await pS({paths:c.paths,state:c.state,runId:t.runId,transactionId:c.applied.transactionId,archiveRef:c.applied.archiveRef,derivedReport:YB(t,c)}):await jl({paths:a,state:c.state,runId:t.runId,archiveRef:c.applied.archiveRef,allowMissingReport:!0,history:!0});if(l.transactionId!==c.applied.transactionId)throw new Error("Native SDK Archive recovery receipt belongs to another transaction");return l}var gS,mS,vS,mv,wS,hv,Vf,gv,vv=x(()=>{"use strict";Eo();Co();ze();Et();He();fv();Se();Es();gS=[["supervisor.parent.deliver","native-supervisor-parent-deliver"],["archive.prepare","native-archive-preflight"],["archive.execute","native-archive"],["archive.finalize","native-archive-finalize"],["supervisor.cleanup","native-supervisor-cleanup"]];mS=new Map;vS={id:"comet-native-archive-preflight",capabilities:[],supports:e=>e.type==="call_tool"&&e.ref==="native-archive-preflight",async execute(e,t,r){if(!t?.projectRoot||!r)throw new Error("Native Archive preflight requires a bound SDK Run");let n=await JB(r,e,t.projectRoot);return mS.set(zB(r,e,t.projectRoot),n),{status:n.ready?"succeeded":"failed",output:n}}},mv={id:"comet-native-archive-preflight-outcome",version:"1",async validate({run:e,action:t,outcome:r,context:n}){if(!n?.projectRoot||t.claim?.executorId!==vS.id)return{accepted:!1,reason:"Native Archive preflight was not run by the Runtime"};let i=r.output;if(r.status==="failed"&&i?.ready===!1&&r.event===void 0)return{accepted:!0};try{let o=zB(e,t,n.projectRoot),a=mS.get(o);mS.delete(o);let s=a??await JB(e,t,n.projectRoot);return D(r.output)!==D(s)||r.status==="succeeded"!==s.ready||r.event!==void 0?{accepted:!1,reason:"Native Archive preflight changed after execution"}:{accepted:!0}}catch(o){return{accepted:!1,reason:o instanceof Error?o.message:String(o)}}}};wS={id:"comet-native-archive-apply",capabilities:[],supports:e=>e.type==="call_tool"&&e.ref==="native-archive",async execute(e,t,r){if(!t?.projectRoot||!r)throw new Error("Native Archive requires a bound SDK Run");let n=await hS(r,e,t.projectRoot),i=await VB(n);return{status:"succeeded",output:{transactionId:i.id,archiveRef:i.archive_ref,stateVersion:i.start_state_version,specCount:i.spec_changes.length}}}};hv={id:"comet-native-archive-apply-outcome",version:"1",async validate({run:e,action:t,outcome:r,context:n}){if(!n?.projectRoot||t.claim?.executorId!==wS.id||r.event!==void 0)return{accepted:!1,reason:"Native Archive Specs were not applied by the Runtime"};try{if(r.status==="failed"){let c=a5(t);if(!c||!n5(r.output,c))return{accepted:!1,reason:"Native Archive lacks a matching rejected prewrite failure"};let{state:l,paths:u}=await hS(e,t,n.projectRoot);return await Mn(u,{kind:"archive",change:l.name})?{accepted:!1,reason:"Native Archive has a transaction; recover its actual progress"}:{accepted:!0}}let i=t.status==="unknown",{state:o,paths:a}=await hS(e,t,n.projectRoot,i);if(r.status!=="succeeded")return{accepted:!1,reason:"Unexpected Native Archive apply event"};let s={...await fS({paths:a,state:o})};return D(r.output)===D(s)?{accepted:!0}:{accepted:!1,reason:"Native Archive Spec application changed before commit"}}catch(i){return{accepted:!1,reason:i instanceof Error?i.message:String(i)}}}};Vf={id:"comet-native-archive-finalize",capabilities:[],supports:e=>e.type==="call_tool"&&e.ref==="native-archive-finalize",async execute(e,t,r){if(!t?.projectRoot||!r)throw new Error("Native Archive finalization requires a bound SDK Run");let n=await KB(r,e,t.projectRoot),{state:i,paths:o,applied:a}=n,s=await pS({paths:o,state:i,runId:r.runId,transactionId:a.transactionId,archiveRef:a.archiveRef,derivedReport:YB(r,n)});if(s.transactionId!==a.transactionId||s.archiveRef!==a.archiveRef)throw new Error("Native SDK Archive receipt does not match applied Specs");return{status:"succeeded",output:s}}},gv={id:"comet-native-archive-finalize-outcome",version:"1",async validate({run:e,action:t,outcome:r,context:n}){if(!n?.projectRoot||t.claim?.executorId!==Vf.id||r.event!==void 0)return{accepted:!1,reason:"Native Archive was not finalized by the Runtime"};try{let{state:i,paths:o,applied:a}=await GB(e,t,n.projectRoot,r.status==="succeeded");if(r.status!=="succeeded")return{accepted:!1,reason:"Native Archive finalization did not succeed"};let s=await jl({paths:o,state:i,runId:e.runId,archiveRef:a.archiveRef,history:t.status==="unknown",allowMissingReport:!0});return s.transactionId!==a.transactionId||s.archiveRef!==a.archiveRef||D(r.output)!==D(s)?{accepted:!1,reason:"Native Archive receipt changed before commit"}:{accepted:!0}}catch(i){return{accepted:!1,reason:i instanceof Error?i.message:String(i)}}}}});function ZB(e){return["archive.prepare","archive.execute","supervisor.child.verifier","supervisor.child.integration-repair"].some(t=>e==="ACTION_FAILED: "+t)}function wv(e,t){return t?.workflow.hash===D(Bn(e))}var yv=x(()=>{"use strict";ze()});import{promises as s5}from"node:fs";import eW from"node:path";async function kv(e,t){let r=M(e.state),n=e.input,i=await Te(t);if(r.phase!=="shape"||r.archived||n.name!==r.name||typeof n.artifactRootRef!="string"||i?.native.artifact_root!==n.artifactRootRef)throw new Error("Native SDK capability association is not bound to the current Shape");let o=await we(t,n.artifactRootRef),a=eW.join(o.changesDir,r.name,"capability-association.yaml"),s=eW.relative(t,a),c=await ie(t,s,{label:"Native capability association",expected:"file"});return{paths:o,file:a,inspected:c}}var tW,bv,Av,rW=x(()=>{"use strict";lt();Et();St();He();Se();tW={id:"comet-native-disassociate",capabilities:[],supports(e){return e.stepId==="shape.disassociate"&&e.ref==="native-disassociate"},async execute(e,t,r){if(!t?.projectRoot||!r)throw new Error("Native SDK project context is required");let n=e.input.activation,i=M(r.state);if(n?.expectedStateVersion!==i.state_version)throw new Error("Native SDK capability revocation references a stale Shape");let o=await kv(r,t.projectRoot);return await $e(o.paths,async()=>{let a=await kv(r,t.projectRoot);a.inspected.exists&&await s5.rm(a.file)}),{status:"succeeded",output:{removed:!0}}}},bv={id:"comet-native-disassociate-command",version:"1",async validate({run:e,name:t,input:r,context:n}){let i=M(e.state);if(t!=="disassociate-capability"||i.phase!=="shape"||!["active","await-user"].includes(i.status)||i.archived||r===null||typeof r!="object"||Array.isArray(r)||Object.keys(r).sort().join(",")!=="expectedStateVersion"||r.expectedStateVersion!==i.state_version||!n?.projectRoot)return{accepted:!1,reason:"Native capability revocation is stale or outside Shape"};try{return(await kv(e,n.projectRoot)).inspected.exists?{accepted:!0}:{accepted:!1,reason:"Native capability association does not exist"}}catch(o){return{accepted:!1,reason:o instanceof Error?o.message:String(o)}}}},Av={id:"comet-native-disassociate-outcome",version:"1",async validate({run:e,action:t,outcome:r,context:n}){if(r.status!=="succeeded"||t.stepId!=="shape.disassociate"||!n?.projectRoot||r.output?.removed!==!0)return{accepted:!1,reason:"Native capability revocation has no successful receipt"};try{return(await kv(e,n.projectRoot)).inspected.exists?{accepted:!1,reason:"Native capability association still exists"}:{accepted:!0}}catch(i){return{accepted:!1,reason:i instanceof Error?i.message:String(i)}}}}});import Rv from"node:path";async function yS(e,t,r){Zh(r);let n=M(e.state),i=e.input,o=await Te(t);if(n.archived||n.status==="done"||i.name!==n.name||typeof i.artifactRootRef!="string"||o?.native.artifact_root!==i.artifactRootRef)throw new Error("Native SDK capability removal requires an active change");let a=await we(t,i.artifactRootRef);if(!(await ie(t,Rv.relative(t,Rv.join(a.specsDir,r,"spec.md")),{label:"Canonical Native spec",expected:"file"})).exists)throw new Error(`Canonical Native spec does not exist: ${r}`);if((await ie(t,Rv.relative(t,Rv.join(a.changesDir,n.name,"specs",r)),{label:"Native proposed spec",expected:"directory"})).exists)throw new Error(`Capability ${r} cannot be proposed and removed together`);return n}var Nv,nW,Sv,iW=x(()=>{"use strict";lt();Xd();Et();He();Se();Nv={id:"comet-native-remove-command",version:"1",async validate({run:e,name:t,input:r,context:n}){let i=M(e.state);if(t!=="remove-capability"||!["active","await-user","blocked"].includes(i.status)||r===null||typeof r!="object"||Array.isArray(r)||Object.keys(r).sort().join(",")!=="capability,expectedStateVersion"||typeof r.capability!="string"||r.expectedStateVersion!==i.state_version||!n?.projectRoot)return{accepted:!1,reason:"Native capability removal is stale or invalid"};try{return await yS(e,n.projectRoot,r.capability),{accepted:!0}}catch(o){return{accepted:!1,reason:o instanceof Error?o.message:String(o)}}}},nW={id:"comet-native-remove",capabilities:[],supports(e){return e.stepId==="shape.remove"&&e.ref==="native-remove"},async execute(e,t,r){if(!t?.projectRoot||!r)throw new Error("Native SDK project context is required");let n=e.input.activation,i=M(r.state);if(typeof n?.capability!="string"||n.expectedStateVersion!==i.state_version)throw new Error("Native capability removal references a stale change");return await yS(r,t.projectRoot,n.capability),{status:"succeeded",output:{capability:n.capability}}}},Sv={id:"comet-native-remove-outcome",version:"1",async validate({run:e,action:t,outcome:r,context:n}){let i=t.input.activation;if(r.status!=="succeeded"||t.stepId!=="shape.remove"||!n?.projectRoot||typeof i?.capability!="string"||r.output?.capability!==i.capability)return{accepted:!1,reason:"Native capability removal has no matching receipt"};try{return await yS(e,n.projectRoot,i.capability),{accepted:!0}}catch(o){return{accepted:!1,reason:o instanceof Error?o.message:String(o)}}}}});function zi(e,t){let r=t.stepId==="supervisor.child.verifier",n=t.input.activation,i=e.actions.findIndex(o=>o.id===t.id);for(let o=i-1;o>=0;o-=1){let a=e.actions[o];if(a.stepId==="shape.revalidate"||a.stepId==="shape.prepare")break;if(!(a.status!=="succeeded"||a.outcome?.output?.requireIndependentReview!==!0)){if(r){let c=a.input.activation;if(a.stepId==="supervisor.child.builder"&&c?.child===n?.child)return!0}else if(["build.builder","supervisor.parent.builder"].includes(a.stepId))return!0}}return!1}var Mf=x(()=>{"use strict"});function kS(e,t){let r=M(e.state),n=new Map;for(let i of e.actions){if(i.status!=="succeeded")continue;let o=i.outcome?.output;if(i.stepId==="supervisor.prepare"){let a=It(t,r.name),s=Nt(r.name);if(typeof o?.integrationWorktree!="string"||!ye(o.integrationWorktree,a)||o.integrationBranch!==s)throw new Error("Native 需求修订的集成工作区归属不一致");n.set(s,{kind:"integration",child:null,worktree:a,branch:s,head:""})}if(i.stepId==="supervisor.child.prepare"){if(typeof o?.child!="string")throw new Error("Native 需求修订缺少 Child 归属");let a=o.child,s=zt(t,r.name,a),c=`comet/supervisor/${r.name}/${a}`;if(typeof o.worktree!="string"||!ye(o.worktree,s)||o.branch!==c)throw new Error("Native 需求修订的 Child 工作区归属不一致");n.set(c,{kind:"child",child:a,worktree:s,branch:c,head:""})}}return[...n.values()].map(i=>{let o=ue(i.worktree),a=pe(i.worktree,i.branch);if(o.currentBranch!==i.branch||!o.primaryWorktreeRoot||!ye(o.primaryWorktreeRoot,t)||!a)throw new Error("Native 需求修订的 Git 工作区身份已变化");return{...i,head:a}})}function Fs(e,t,r){let o=[...e.actions].reverse().find(a=>a.stepId==="shape.revise"&&a.status==="succeeded")?.outcome?.output?.workspaces?.find(a=>typeof a.worktree=="string"&&ye(a.worktree,t)&&a.branch===r);if(!o)return null;if(pe(t,r)!==o.head)throw new Error("Native 修订后保留的工作区提交已变化,请核对原现场");return o}var bS=x(()=>{"use strict";it();Se();rn()});function AS(e){if(!e||typeof e!="object"||Array.isArray(e))return null;let t=e;return Object.keys(t).sort().join(",")!=="archiveActionId,expectedStateVersion,proposalHash,reason"||typeof t.reason!="string"||!t.reason.trim()||typeof t.expectedStateVersion!="number"||typeof t.proposalHash!="string"||typeof t.archiveActionId!="string"?null:t}async function oW(e,t,r){let n=e.actions.find(i=>i.id===t.archiveActionId);if(!n||n.status!=="cancelled"||!["archive.prepare","archive.execute"].includes(n.stepId))throw new Error("Native implementation revision has no original pending Archive action");return{drift:!0,requirementsChanged:!1,driftKind:"implementation-changed",archiveStep:n.stepId,reason:t.reason.trim()}}function NS(e){return e.waits.find(t=>{if(t.status!=="pending"||t.stepId!=="build.resume")return!1;let r=t.proposal?.activation?.failedBuilderActionId;return e.actions.some(n=>n.id===r&&n.stepId==="build.builder"&&n.status==="failed")})}function SS(e,t,r){if(e.actions.some(o=>["running","unknown"].includes(o.status)))return!1;if(["verify","archive"].includes(t.phase))return r===void 0;if(t.phase!=="build")return!1;if(t.children_contract_ref)return r===void 0;let n=_v(e);if(n)return r===n;let i=NS(e);return i!==void 0&&i.proposalHash===r}function _v(e){let t=M(e.state);if(t.phase!=="build"||t.children_contract_ref||!["running","waiting"].includes(e.status)||e.actions.some(a=>["running","unknown"].includes(a.status)))return null;let r=e.actions.filter(a=>a.status==="pending");if(r.length!==1||r[0].stepId!=="build.builder")return null;let{id:n,attempt:i,inputHash:o}=r[0];return D({actionId:n,attempt:i,inputHash:o})}var Ev,RS,Cv,Iv,aW,xv,ES=x(()=>{"use strict";ze();Se();bS();Ev={id:"comet-native-implementation-revision-command",version:"1",async validate({run:e,name:t,input:r,context:n}){let i=M(e.state),o=AS(r),a=e.actions.filter(l=>l.status==="pending"),s=a[0],c=[...e.waits].reverse().find(l=>l.stepId==="verify.confirm"&&l.status==="resolved"&&l.decision?.choice==="approved");return t!=="revise-implementation"||!o||!n?.projectRoot||i.phase!=="archive"||i.status!=="active"||i.archived||i.state_version!==o.expectedStateVersion||!c||c.proposalHash!==o.proposalHash||a.length!==1||s.id!==o.archiveActionId||!["archive.prepare","archive.execute"].includes(s.stepId)||e.actions.some(l=>["running","unknown"].includes(l.status))||e.actions.some(l=>l.stepId==="archive.execute"&&l.status==="succeeded")||e.waits.some(l=>l.status==="pending")||e.evidenceWaits?.some(l=>l.status==="pending")||e.ready.length>0?{accepted:!1,reason:"Native implementation revision is stale or Archive is already in progress"}:{accepted:!0}}};RS={id:"comet-native-revise-implementation",capabilities:[],supports:e=>e.stepId==="repair.implementation"&&e.ref==="native-revise-implementation",async execute(e,t,r){let n=AS(e.input.activation);if(!r||!n||!t?.projectRoot)throw new Error("Native implementation revision lacks its input");return{status:"succeeded",output:await oW(r,n,t.projectRoot)}}},Cv={id:"comet-native-implementation-revision-outcome",version:"1",async validate({run:e,action:t,outcome:r,context:n}){let i=AS(t.input.activation);if(!i||!n?.projectRoot||r.status!=="succeeded"||t.claim?.executorId!==RS.id)return{accepted:!1,reason:"Native implementation revision has no matching read-only result"};let o=await oW(e,i,n.projectRoot);return{accepted:D(r.output)===D(o),reason:"Native candidate changed during revision"}}};Iv={id:"comet-native-revise-command",version:"1",async validate({run:e,name:t,input:r}){let n=M(e.state);return t!=="revise-requirements"||n.archived||!["active","await-user","blocked"].includes(n.status)||e.status==="completed"||r===null||typeof r!="object"||Array.isArray(r)||!["expectedStateVersion,reason","expectedStateVersion,proposalHash,reason"].includes(Object.keys(r).sort().join(","))||!SS(e,n,r.proposalHash)||r.expectedStateVersion!==n.state_version||typeof r.reason!="string"||!r.reason.trim()||e.actions.some(i=>i.stepId==="archive.execute"&&["succeeded","running","unknown"].includes(i.status))?{accepted:!1,reason:"Native requirements revision is stale or cannot interrupt Archive application"}:{accepted:!0}}},aW={id:"comet-native-revise-requirements",capabilities:[],supports(e){return e.stepId==="shape.revise"&&e.ref==="native-revise-requirements"},async execute(e,t,r){if(!r)throw new Error("Native SDK Run is required");let n=e.input.activation,i=M(r.state);if(typeof n?.reason!="string"||!n.reason.trim()||n.expectedStateVersion!==i.state_version)throw new Error("Native requirements revision references a stale change");if(i.children_contract_ref&&!t?.projectRoot)throw new Error("Native Supervisor 需求修订缺少实际项目");let o=i.children_contract_ref?kS(r,t.projectRoot):void 0;return{status:"succeeded",output:{reason:n.reason.trim(),...o?{workspaces:o}:{}}}}},xv={id:"comet-native-revise-outcome",version:"1",validate({run:e,action:t,outcome:r,context:n}){let i=t.input.activation,o=M(e.state),a=!0;try{o.children_contract_ref&&(a=!!n?.projectRoot&&D(r.output?.workspaces??null)===D(kS(e,n.projectRoot)))}catch{a=!1}return{accepted:r.status==="succeeded"&&t.stepId==="shape.revise"&&typeof i?.reason=="string"&&r.output?.reason===i.reason.trim()&&a,reason:"Native requirements revision has no matching receipt"}}}});function ur(e){for(let t=e.actions.length-1;t>=0;t--){let r=e.actions[t];if((r.id===e.state.children_contract_ref||r.stepId==="shape.revalidate")&&r.status==="succeeded")return e.actions.slice(t+1)}return e.actions}function CS(e){if(!Number.isSafeInteger(e.maxParallel)||e.maxParallel<1)throw new Error("Native Supervisor maxParallel must be a positive integer");let t=new Set(e.contract.children.map(o=>o.name)),r=new Set(e.integrated),n=new Set(e.active);if(r.size!==e.integrated.length||n.size!==e.active.length)throw new Error("Native Supervisor child facts contain duplicate names");for(let o of[...r,...n]){if(!t.has(o))throw new Error(`Native Supervisor fact names unknown child ${o}`);if(r.has(o)&&n.has(o))throw new Error(`Native Supervisor child ${o} cannot be both integrated and active`)}let i=Math.max(0,e.maxParallel-n.size);return e.contract.children.filter(o=>!r.has(o.name)&&!n.has(o.name)&&o.depends_on.every(a=>r.has(a))).slice(0,i).map(o=>o.name)}var Hs=x(()=>{"use strict"});async function $l(e,t){let r=M(e.state),n=e.input;if(!["build","verify","archive"].includes(r.phase)||r.name!==n.name||!r.children_contract_ref||typeof n.artifactRootRef!="string")throw new Error("Native SDK Supervisor preparation lacks a confirmed child plan");let i=await Te(t);if(!i||i.native.artifact_root!==n.artifactRootRef)throw new Error("Native SDK Supervisor project configuration changed");let o=e.outputs["shape.revalidate"]?.value??e.outputs["shape.prepare"]?.value,a=r.children_contract??o?.children?.contract;if(!a)throw new Error("Native SDK Supervisor lacks its original approved children plan; explicitly revise requirements to confirm it");let s=r.workspace.change_branch??r.workspace.target_branch;if(!s)throw new Error("Native SDK Supervisor requires a bound Git target branch");return{state:r,config:i,contract:a,targetBranch:s}}async function Rn(e,t){let r=await $l(e,t),n=pe(t,r.targetBranch);if(!n)throw new Error("Native SDK Supervisor target branch has no commit");return{...r,targetCommit:n}}function c5(e){let t=e.input.activation;if(!t||typeof t.child!="string"||typeof Ke(t)!="string"||typeof t.integrationBranch!="string"||typeof t.integrationWorktree!="string"||typeof t.targetCommit!="string")throw new Error("Native SDK Supervisor child preparation lacks its activation");return{...t,contractRef:Ke(t)}}async function _S(e,t,r){let n=await Rn(e,r),i=c5(t);if(!n.contract.children.some(({name:a})=>a===i.child)||Ke(i,e)!==n.state.children_contract_ref||i.integrationBranch!==Nt(n.state.name)||!ye(i.integrationWorktree,It(r,n.state.name))||pe(r,i.integrationBranch)!==i.targetCommit)throw new Error("Native SDK Supervisor child preparation no longer matches its parent plan");if(ue(i.integrationWorktree).currentBranch!==i.integrationBranch)throw new Error("Native SDK Supervisor integration worktree changed before child preparation");return{...n,input:i}}var IS,Pv,xS,Tv,Qs=x(()=>{"use strict";Cr();it();Et();Se();bS();rn();IS={id:"native-supervisor-prepare",capabilities:[],supports(e){return e.stepId==="supervisor.prepare"&&e.type==="call_tool"},async preflight(e,t,r){if(!t?.projectRoot||!r||!this.supports(e))throw new Error("Native SDK Supervisor preparation requires a bound Run and project");let n=await Rn(r,t.projectRoot);Fs(r,It(t.projectRoot,n.state.name),Nt(n.state.name))},async execute(e,t,r){if(!t?.projectRoot||!r||!this.supports(e))throw new Error("Native SDK Supervisor preparation requires a bound Run and project");let n=await Rn(r,t.projectRoot),i=Fs(r,It(t.projectRoot,n.state.name),Nt(n.state.name)),o=await zh({projectRoot:t.projectRoot,parent:n.state.name,targetBranch:n.targetBranch,sourceConfig:n.config});return{status:"succeeded",output:{contractRef:n.state.children_contract_ref,integrationBranch:o.binding.changeBranch,integrationWorktree:o.projectRoot,targetBranch:n.targetBranch,targetCommit:n.targetCommit,integrationCommit:i?.head??n.targetCommit,maxParallelChildren:n.state.coordination_mode==="single-session"?1:n.config.native.max_parallel_children??Mu}}}},Pv={id:"native-supervisor-prepare-outcome",version:"1",async validate({run:e,action:t,outcome:r,context:n}){if(r.status==="failed")return{accepted:!0};if(!n?.projectRoot||!IS.supports(t))return{accepted:!1,reason:"Native SDK Supervisor preparation lacks its project"};try{let i=await Rn(e,n.projectRoot),o=r.output,a=It(n.projectRoot,i.state.name),s=Nt(i.state.name),c=Fs(e,a,s);if(!o||Ke(o,e,t)!==i.state.children_contract_ref||o.integrationBranch!==s||typeof o.integrationWorktree!="string"||!ye(o.integrationWorktree,a)||o.targetBranch!==i.targetBranch||o.targetCommit!==i.targetCommit||(o.integrationCommit??o.targetCommit)!==(c?.head??i.targetCommit))throw new Error("Native SDK Supervisor preparation result does not match its plan");if(ue(a).currentBranch!==s)throw new Error("Native SDK Supervisor integration worktree has a different branch");if(pe(a,s)!==(c?.head??i.targetCommit))throw new Error("Native SDK Supervisor integration worktree head changed");return{accepted:!0}}catch(i){return{accepted:!1,reason:i instanceof Error?i.message:String(i)}}}},xS={id:"native-supervisor-child-prepare",capabilities:[],supports(e){return e.stepId==="supervisor.child.prepare"&&e.type==="call_tool"},async preflight(e,t,r){if(!t?.projectRoot||!r||!this.supports(e))throw new Error("Native SDK Supervisor child preparation requires a bound Run and project");let n=await _S(r,e,t.projectRoot);Fs(r,zt(t.projectRoot,n.state.name,n.input.child),`comet/supervisor/${n.state.name}/${n.input.child}`)},async execute(e,t,r){if(!t?.projectRoot||!r||!this.supports(e))throw new Error("Native SDK Supervisor child preparation requires a bound Run and project");let n=await _S(r,e,t.projectRoot);Fs(r,zt(t.projectRoot,n.state.name,n.input.child),`comet/supervisor/${n.state.name}/${n.input.child}`);let i=await Kh({projectRoot:t.projectRoot,parent:n.state.name,child:n.input.child,targetBranch:n.input.integrationBranch,sourceConfig:n.config});return{status:"succeeded",output:{child:n.input.child,contractRef:n.input.contractRef,worktree:i.projectRoot,branch:i.binding.changeBranch,baseCommit:n.input.targetCommit}}}},Tv={id:"native-supervisor-child-prepare-outcome",version:"1",async validate({run:e,action:t,outcome:r,context:n}){if(r.status==="failed")return{accepted:!0};if(!n?.projectRoot||!xS.supports(t))return{accepted:!1,reason:"Native SDK Supervisor child preparation lacks its project"};try{let i=await _S(e,t,n.projectRoot),o=r.output,a=zt(n.projectRoot,i.state.name,i.input.child),s=`comet/supervisor/${i.state.name}/${i.input.child}`;if(!o||o.child!==i.input.child||Ke(o,e)!==Ke(i.input,e)||typeof o.worktree!="string"||!ye(o.worktree,a)||o.branch!==s||o.baseCommit!==i.input.targetCommit)throw new Error("Native SDK Supervisor child preparation result does not match its plan");let c=ue(a),l=Fs(e,a,s);if(c.currentBranch!==s||pe(a,s)!==o.baseCommit&&!l)throw new Error("Native SDK Supervisor child worktree changed before Builder dispatch");return{accepted:!0}}catch(i){return{accepted:!1,reason:i instanceof Error?i.message:String(i)}}}}});import{promises as cW}from"node:fs";import ln from"node:path";function Dl(e){let t=e?.activation;if(!t||typeof t.child!="string"||typeof t.candidateCommit!="string"||typeof t.integrationCommit!="string"||typeof t.checksActionId!="string"&&typeof t.mergeActionId!="string"||typeof Ke(t)!="string")throw new Error("Native Supervisor child archive lacks its activation");return{...t,contractRef:Ke(t)}}function PS(e,t,r,n){for(let i of[...ur(e)].reverse()){if(i.stepId!==t||i.status!=="succeeded"||!i.outcome||i.input?.activation?.child!==r)continue;let a=i.outcome.output;if(!(!a||!n(a)))return{action:i,output:a}}return null}async function lW(e,t,r,n=!1){let i=await Rn(e,r),o=i.state,a=Dl(t.input);if(o.phase!=="build"||o.status!=="active"||!o.children_contract_ref||Ke(a,e)!==o.children_contract_ref||!i.contract.children.some(({name:re})=>re===a.child)||!Us.test(a.candidateCommit)||!Us.test(a.integrationCommit))throw new Error("Native Supervisor child archive does not match the confirmed plan");let s=a.checksActionId?e.actions.find(re=>re.id===a.checksActionId):void 0,c=s?.outcome?.output;if(s&&(s.stepId!=="supervisor.child.integration-checks"||s.status!=="succeeded"||c?.candidateId!==a.integrationCommit||typeof c.completedAt!="string"))throw new Error("Native legacy archive lacks its original accepted integration result");let l=a.mergeActionId??s?.input?.activation?.mergeActionId,u=e.actions.find(re=>re.id===l),f=u?.outcome?.output,d=a.repairActionId??s?.input?.activation?.repairActionId,p=d?e.actions.find(re=>re.id===d):void 0,m=p?.outcome?.output;if(u?.stepId!=="supervisor.child.integrate"||u.status!=="succeeded"||f?.child!==a.child||(p?p.stepId!=="supervisor.child.integration-repair"||p.status!=="succeeded"||p.input.activation?.mergeActionId!==u.id||p.input.activation.child!==a.child||p.input.activation.candidateCommit!==a.candidateCommit||Ke(p.input.activation,e)!==o.children_contract_ref||m?.integrationCommit!==a.integrationCommit:f.integrationCommit!==a.integrationCommit))throw new Error("Native Supervisor child archive lacks its accepted integration task");let h=c?.completedAt??te((e.outputs["supervisor.prepare"]?.value).integrationWorktree,["show","-s","--format=%cI",a.integrationCommit]).trim(),g=PS(e,"supervisor.child.verifier",a.child,re=>{let nt=re.evidence;return re.verdict==="pass"&&re.candidateCommit===a.candidateCommit&&typeof nt?.summary=="string"&&!!nt.summary.trim()});if(!g||!g.action.claim?.sessionId)throw new Error("Native Supervisor child archive lacks its passing Verifier");let v=g.output.evidence,w=PS(e,"supervisor.child.builder",a.child,re=>re.candidateCommit===a.candidateCommit),y=["1","2","3"].includes(g.action.executionOrigin?.workflow.version??""),R=y?PS(e,"supervisor.child.checks",a.child,re=>re.candidateId===a.candidateCommit):null;if(y&&!R)throw new Error("Legacy Child archive lacks its original accepted checks");let N=R?.output,b=e.outputs["supervisor.prepare"]?.value;if(typeof b?.integrationWorktree!="string"||typeof b.integrationBranch!="string")throw new Error("Native Supervisor child archive lacks its integration workspace");let E=zt(r,o.name,a.child),I=`comet/supervisor/${o.name}/${a.child}`;if(ue(E).currentBranch!==I)throw new Error("Native Supervisor child worktree moved before the child archive");if(ue(b.integrationWorktree).currentBranch!==b.integrationBranch)throw new Error("Native Supervisor integration worktree moved before the child archive");let W=te(E,["ls-files","--others","--exclude-standard","-z"]).split("\0").filter(re=>re&&re!==".comet/config.yaml").map(re=>re.replaceAll("\\","/"));if(!n&&(!ho(E,W)||!ho(b.integrationWorktree)))throw new Error("Native Supervisor child archive requires clean worktrees");let F=new Map;if(Array.isArray(v.acceptance))for(let re of v.acceptance)typeof re?.id!="string"||typeof re?.result!="string"||F.set(re.id,typeof re.reason=="string"?re.reason:"");let G=oi(i.contract,a.child);for(let{id:re}of G)if(!F.has(re))throw new Error(`Native Supervisor child archive evidence does not cover acceptance ${re}`);let Z=(N?.checks??[]).map(re=>{if(typeof re.id!="string"||typeof re.name!="string"||!Array.isArray(re.argvDisplay)||typeof re.cwdRef!="string"||re.status!=="passed"||!Number.isSafeInteger(re.durationMs))throw new Error("Native Supervisor child archive requires passed Child checks");return{id:re.id,name:re.name,argvDisplay:re.argvDisplay,cwdRef:re.cwdRef,status:re.status,exitCode:typeof re.exitCode=="number"?re.exitCode:null,durationMs:re.durationMs}}),Ae=Array.isArray(v.risks)?v.risks.filter(re=>typeof re=="string"):[];return{parent:o.name,maxParallelChildren:i.state.coordination_mode==="single-session"?1:i.config.native.max_parallel_children??Mu,child:a.child,language:o.language,targetBranch:i.targetBranch,worktree:E,branch:I,candidateCommit:a.candidateCommit,integrationBranch:b.integrationBranch,integrationWorktree:b.integrationWorktree,integrationCommit:a.integrationCommit,builderSessionId:w?.action.claim?.sessionId??null,builderSummary:typeof w?.output.summary=="string"?w.output.summary:null,verifierSessionId:g.action.claim.sessionId,verifierSummary:v.summary,verifierRisks:Ae,verifierAcceptance:F,childChecks:Z,...y?{}:{reportedChecks:Ti(v.checks??[])},childChecksCompletedAt:N?.completedAt??h,integrationChecksCompletedAt:h,scopedAcceptance:G}}async function u5(e,t,r,n){let i=await Rn(e,r),o=await we(r,i.config.native.artifact_root),a=ln.join(o.changesDir,n.parent),s=await Pe({root:a,ref:i.state.brief,includeHash:!1}),c=await Promise.all(i.state.spec_changes.flatMap(d=>d.source?[Pe({root:a,ref:d.source,includeHash:!1})]:[])),l=n.language==="zh-CN"?"子任务归档":"Archived Child",u=n.scopedAcceptance.map(d=>`- ${d.id}: ${d.text}`).join(`
|
|
393
|
+
`),f=[s,...c].map(d=>`- ${d.ref}`).join(`
|
|
394
|
+
`);return{"brief.md":`# ${n.child}
|
|
395
|
+
|
|
396
|
+
${l}: ${n.parent}
|
|
397
|
+
|
|
398
|
+
${n.language==="zh-CN"?"本归档仅覆盖以下已确认验收项。Spec 是 Parent 已确认内容的快照,不表示独立 Child Spec 变更或新增验收。":"This archive covers only the confirmed acceptance below. The Spec is a snapshot of the confirmed Parent, not an independent Child Spec change or additional acceptance."}
|
|
399
|
+
|
|
400
|
+
${u}
|
|
401
|
+
|
|
402
|
+
[Parent Spec](spec.md) · [${n.language==="zh-CN"?"来源与原始简报":"Sources and original brief"}](archive-source.md) · [${n.language==="zh-CN"?"验收记录":"Verification"}](verification.md)
|
|
403
|
+
`,"spec.md":c.length===0?`# Parent Spec
|
|
404
|
+
|
|
405
|
+
No Spec change was declared by the confirmed Parent.
|
|
406
|
+
`:c.length===1?c[0].text:c.map(d=>`# ${d.ref}
|
|
407
|
+
|
|
408
|
+
${d.text}`).join(`
|
|
409
|
+
|
|
410
|
+
`),"archive-source.md":`# ${n.language==="zh-CN"?"归档材料来源":"Archive material sources"}
|
|
411
|
+
|
|
412
|
+
- Parent Run: ${e.runId}
|
|
413
|
+
- Archive Action: ${t.id}
|
|
414
|
+
- Contract: ${Ke(Dl(t.input),e)}
|
|
415
|
+
- Candidate: ${n.candidateCommit}
|
|
416
|
+
- Verifier: ${n.verifierSessionId}
|
|
417
|
+
- Integration Action: ${Dl(t.input).mergeActionId??Dl(t.input).checksActionId}
|
|
418
|
+
|
|
419
|
+
${f}
|
|
420
|
+
|
|
421
|
+
## ${n.language==="zh-CN"?"Parent 原始简报":"Original Parent brief"}
|
|
422
|
+
|
|
423
|
+
${s.text}`}}async function d5(e,t,r){let n=[];for(let i of Object.keys(t))await Pe({root:e,ref:i}).catch(a=>{if(a.code==="ENOENT")return null;throw a})||n.push(i);if(!r)for(let i of n)await qe(ln.join(e,i),t[i],{containedRoot:e});return n}function f5(e){let t=e.scopedAcceptance.filter(({id:n})=>l5.test(n)).map(({id:n,source:i,text:o})=>{let a=e.verifierAcceptance.get(n);return{id:n,source:i,text:o,result:"passed",reason:a?Ct(a):null}}),r=Gc({name:e.child,language:e.language,workspace:{isolation:"worktree",change_branch:e.branch,target_branch:e.targetBranch,finish:"merge"}});return M({...r,created_at:e.childChecksCompletedAt,phase:"archive",status:"done",archived:!0,loop:{...r.loop,iteration:1,attempt:1,stage:"done",next_action:null},acceptance:t,builder_handoff:{candidate_id:e.candidateCommit,identity_provider:$r,builder_execution_ref:e.builderSessionId??e.verifierSessionId,iteration:1,summary:Ct(e.builderSummary??e.verifierSummary),addressed_acceptance_ids:t.map(({id:n})=>n),checks:e.childChecks.map(n=>({name:Ct(n.name),result:"passed",note:null})),checks_truncated:!1,known_limits:[],known_limits_truncated:!1,review:null,submitted_at:e.childChecksCompletedAt},verification:{candidate_id:e.candidateCommit,identity_provider:$r,verifier_execution_ref:e.verifierSessionId,iteration:1,attempt:1,assurance:e.builderSessionId===e.verifierSessionId?"self-reviewed":"skill-coordinated",verdict:"pass",...e.reportedChecks?{reported_checks:e.reportedChecks}:{},checks:e.childChecks.map(n=>({id:n.id,name:Ct(n.name),argv_display:n.argvDisplay.map(i=>Ct(i)),argv_truncated:!1,cwd_ref:n.cwdRef,status:"passed",exit_code:n.exitCode,duration_ms:n.durationMs})),summary:Ct(e.verifierSummary),risks:e.verifierRisks.map(n=>Ct(n)),risks_truncated:!1,completed_at:e.integrationChecksCompletedAt},verification_result:"pass",verification_report:"verification.md",history:[]})}async function uW(e,t){let r=await Te(e.worktree);if(!r)throw new Error("Native Supervisor child worktree has no project config");let n=await we(e.worktree,r.native.artifact_root),i=ln.join(n.archiveDir,t),o=ln.resolve(i),a=ln.resolve(n.archiveDir);if(!o.toLowerCase().startsWith(`${a.toLowerCase()}${ln.sep}`)&&o.toLowerCase()!==a.toLowerCase())throw new Error("Native Supervisor child archive path escaped the archive root");return{target:o,relative:ln.relative(e.worktree,o).replaceAll("\\","/"),changesDir:n.changesDir,nativeRoot:n.nativeRoot}}function OS(e){let t=e.integrationChecksCompletedAt.slice(0,10);if(!/^\d{4}-\d{2}-\d{2}$/.test(t))throw new Error("Native Supervisor child archive lacks a valid archive date");return`${t}-${e.child}`}function Ov(e,t,r){let n=te(e,["show","--name-only","--format=",t]).split(`
|
|
424
|
+
`).map(i=>i.trim()).filter(Boolean);if(n.length===0||n.some(i=>!i.startsWith(`${r}/`)))throw new Error(`Native Supervisor child archive commit ${t} touches paths outside ${r}`)}async function p5(e,t,r,n){let i=e.actions.findIndex(s=>s.id===t.id),o=i<0?void 0:e.actions.slice(0,i).reverse().find(s=>s.stepId==="supervisor.child.archive"&&s.status==="succeeded"&&s.input?.activation?.child===r.child),a=o?.outcome?.output;if(!o||o.claim?.executorId!==jv.id||a?.child!==r.child||a.archiveRef!==OS(r)||a.candidateCommit!==Dl(o.input).candidateCommit||a?.baseCommit!==Dl(o.input).integrationCommit||typeof a.archiveCommit!="string"||!Us.test(a.archiveCommit))throw new Error("Native Supervisor child archive lacks its accepted predecessor receipt");Ov(r.worktree,a.archiveCommit,n.relative);for(let[s,c]of[[r.worktree,r.candidateCommit],[r.integrationWorktree,r.integrationCommit]])te(s,["merge-base","--is-ancestor",a.archiveCommit,c])}async function sW(e){try{return await cW.access(e),!0}catch{return!1}}var TS,Us,l5,jv,$v,dW=x(()=>{"use strict";Cr();TS=dr(Ur(),1);it();Sr();dt();Er();Et();He();Se();io();vs();Hs();Qs();ai();rn();Pl();el();Us=/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u,l5=/^A[1-9][0-9]*$/u;jv={id:"native-supervisor-child-archive",capabilities:[],supports(e){return e.stepId==="supervisor.child.archive"&&e.type==="call_tool"},async execute(e,t,r){if(!t?.projectRoot||!r||!this.supports(e))throw new Error("Native Supervisor child archive requires a bound Run and project");let n=await lW(r,e,t.projectRoot);if(pe(n.worktree,n.branch)!==n.candidateCommit)throw new Error("Native Supervisor child worktree moved before the child archive");if(pe(n.integrationWorktree,n.integrationBranch)!==n.integrationCommit)throw new Error("Native Supervisor integration head moved before the child archive");let i=OS(n),o=await uW(n,i),a=null;if(await sW(o.target)&&(a=await Jt(ln.join(o.target,"comet-state.yaml")).catch(()=>null),!a||a.name!==n.child||!a.archived||a.workspace.change_branch!==n.branch))throw new Error("Native Supervisor child archive directory holds another change");let s;if(a?.verification?.candidate_id===n.candidateCommit&&a.verification.verifier_execution_ref===n.verifierSessionId&&a.verification.completed_at===n.integrationChecksCompletedAt){let u=pe(n.worktree,n.branch);if(!u||!Us.test(u))throw new Error("Native Supervisor child worktree has no archive commit");Ov(n.worktree,u,o.relative),s=u}else{if(await sW(ln.join(o.changesDir,n.child)))throw new Error(`Native Supervisor child ${n.child} still has an active change directory; archive it through the normal flow first`);let u=f5(n),f=await u5(r,e,t.projectRoot,n);if(a&&await p5(r,e,n,o),await cW.mkdir(o.target,{recursive:!0}),a){let g={...f,"comet-state.yaml":(0,TS.stringify)(u),"verification.md":$f(u)};for(let[v,w]of Object.entries(g))await qe(ln.join(o.target,v),w,{containedRoot:o.nativeRoot})}else await d5(o.target,f,!1),await qe(ln.join(o.target,"comet-state.yaml"),(0,TS.stringify)(u),{containedRoot:o.nativeRoot}),await nv({file:ln.join(o.target,"verification.md"),state:u});if(await Df({file:ln.join(o.target,"verification.md"),stateVersion:u.state_version})!=="aligned")throw new Error("Native Supervisor child archive report is not aligned");te(n.worktree,["add","--force","--",`${o.relative}/comet-state.yaml`,`${o.relative}/verification.md`,`${o.relative}/brief.md`,`${o.relative}/spec.md`,`${o.relative}/archive-source.md`]);let p=te(n.worktree,["diff","--cached","--name-only","--",o.relative]).split(`
|
|
425
|
+
`).filter(Boolean);if(p.length===0)throw new Error("Native Supervisor child archive produced no committable content");let m=p.filter(g=>!g.startsWith(`${o.relative}/`));if(m.length>0)throw new Error(`Native Supervisor child archive staging left unrelated paths: ${m.join(", ")}`);te(n.worktree,["commit","-m",`chore(native): archive ${n.child}`]);let h=pe(n.worktree,n.branch);if(!h||!Us.test(h))throw new Error("Native Supervisor child archive commit is missing");Ov(n.worktree,h,o.relative),s=h}let c=pe(n.integrationWorktree,n.integrationBranch);if(!c||!Us.test(c))throw new Error("Native Supervisor integration branch has no head");let l=c;try{te(n.integrationWorktree,["merge-base","--is-ancestor",s,c])}catch{te(n.integrationWorktree,["merge","--no-ff","--no-edit",n.branch]);let u=pe(n.integrationWorktree,n.integrationBranch);if(!u||!Us.test(u))throw new Error("Native Supervisor child archive merge produced no head");l=u;let f=te(n.integrationWorktree,["rev-list","--parents","-n","1",l]).split(" ");if(f.length!==3||f[1]!==c||f[2]!==s)throw new Error("Native Supervisor child archive merge is not the expected commit")}if(pe(n.worktree,n.branch)!==s)throw new Error("Native Supervisor child branch moved after the archive commit");return{status:"succeeded",output:{child:n.child,archiveRef:i,candidateCommit:n.candidateCommit,archiveCommit:s,baseCommit:n.integrationCommit,integrationCommit:l,maxParallelChildren:n.maxParallelChildren}}}},$v={id:"native-supervisor-child-archive-outcome",version:"1",async validate({run:e,action:t,outcome:r,context:n}){if(!n?.projectRoot||t.claim?.executorId!==jv.id||r.status!=="succeeded")return{accepted:!1,reason:"Native Supervisor child archive was not executed by Runtime"};try{let i=await lW(e,t,n.projectRoot),o=r.output,a=OS(i);if(!o||o.child!==i.child||o.archiveRef!==a||o.candidateCommit!==i.candidateCommit||o.baseCommit!==i.integrationCommit||typeof o.archiveCommit!="string"||typeof o.integrationCommit!="string")throw new Error("Native Supervisor child archive outcome does not match its binding");let s=await uW(i,a),c=await Jt(ln.join(s.target,"comet-state.yaml"));if(c.name!==i.child||!c.archived||c.status!=="done"||c.verification?.verdict!=="pass"||c.workspace.change_branch!==i.branch)throw new Error("Native Supervisor child archive state does not match the child");if(Ov(i.worktree,o.archiveCommit,s.relative),pe(i.worktree,i.branch)!==o.archiveCommit)throw new Error("Native Supervisor child branch is not at its archive commit");let l=te(i.integrationWorktree,["rev-list","--parents","-n","1",o.integrationCommit]).split(" ");if(!l.includes(o.archiveCommit)||!l.includes(i.integrationCommit))throw new Error("Native Supervisor integration did not receive the child archive commit");if(pe(i.integrationWorktree,i.integrationBranch)!==o.integrationCommit)throw new Error("Native Supervisor integration head moved after the child archive");return{accepted:!0}}catch(i){return{accepted:!1,reason:i instanceof Error?i.message:String(i)}}}}});var fW,Dv,Bv,pW=x(()=>{"use strict";it();Sr();Cr();Se();Mf();Qs();ai();rn();Wd();fW=/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u,Dv={id:"native-supervisor-builder-outcome",version:"1",async validate({run:e,action:t,outcome:r,context:n}){if(r.status==="failed")return{accepted:!0};if(!n?.projectRoot||t.stepId!=="supervisor.child.builder"||t.type!=="handoff")return{accepted:!1,reason:"Native SDK Supervisor Builder result lacks its project"};try{let i=M(e.state),o=await $l(e,n.projectRoot),a=t.input.activation,s=r.output;if(s?.requireIndependentReview!==void 0&&typeof s.requireIndependentReview!="boolean")throw new Error("requireIndependentReview must be a boolean");if(i.phase!=="build"||!t.claim?.sessionId||!a||typeof a.child!="string"||!o.contract.children.some(({name:l})=>l===a.child)||Ke(a,e)!==i.children_contract_ref||typeof a.worktree!="string"||!ye(a.worktree,zt(n.projectRoot,i.name,a.child))||a.branch!==`comet/supervisor/${i.name}/${a.child}`||typeof a.baseCommit!="string"||!fW.test(a.baseCommit)||!s||typeof s.candidateCommit!="string"||!fW.test(s.candidateCommit))throw new Error("Native SDK Supervisor Builder result lacks a claimed child candidate");if(ue(a.worktree).currentBranch!==a.branch||pe(a.worktree,a.branch)!==s.candidateCommit)throw new Error("Native SDK Supervisor Builder candidate does not match its worktree");return Ti(s.checks??[]),te(a.worktree,["merge-base","--is-ancestor",a.baseCommit,s.candidateCommit]),{accepted:!0}}catch(i){return{accepted:!1,reason:i instanceof Error?i.message:String(i)}}}},Bv={id:"native-supervisor-verifier-outcome",version:"1",async validate({run:e,action:t,outcome:r,context:n}){if(r.status==="failed")return{accepted:!0};if(!n?.projectRoot||t.stepId!=="supervisor.child.verifier"||t.type!=="handoff")return{accepted:!1,reason:"Native SDK Supervisor Verifier lacks its project"};try{let i=M(e.state),o=await $l(e,n.projectRoot),a=t.input.activation,s=r.output,c=s?.evidence;if(i.phase!=="build"||!t.claim?.sessionId||!a||typeof a.child!="string"||!o.contract.children.some(({name:f})=>f===a.child)||Ke(a,e)!==i.children_contract_ref||typeof a.worktree!="string"||!ye(a.worktree,zt(n.projectRoot,i.name,a.child))||typeof a.candidateCommit!="string"||typeof a.builderSessionId!="string"||zi(e,t)&&t.claim.sessionId===a.builderSessionId||!s||s.candidateCommit!==a.candidateCommit||!["pass","fail","blocked"].includes(String(s.verdict))||!c||typeof c.summary!="string"||!c.summary.trim()||!Array.isArray(c.checks))throw new Error("Native SDK Supervisor Verifier lacks a bound result or required independent session");let l=Ti(c.checks),u=Bh(c.acceptance);return Wh({verdict:s.verdict,acceptance:u},{acceptanceIds:oi(o.contract,a.child).map(({id:f})=>f),requiredChecksPassed:l.every(f=>f.result==="passed")}),{accepted:!0}}catch(i){return{accepted:!1,reason:i instanceof Error?i.message:String(i)}}}}});function jS(e,t){let n=[...e.actions].reverse().find(i=>i.stepId===t&&i.status==="succeeded")?.outcome?.output;return n&&typeof n=="object"&&!Array.isArray(n)?n:null}function mW(e,t,r){let n=jS(e,"supervisor.prepare"),i=It(t,r.name),o=Nt(r.name);if(!n||Ke(n,e)!==r.children_contract_ref||typeof n.integrationWorktree!="string"||!ye(n.integrationWorktree,i)||n.integrationBranch!==o)throw new Error("Native SDK Supervisor cleanup lacks its integration workspace");let a=new Map;for(let s of ur(e)){if(s.stepId!=="supervisor.child.prepare"||s.status!=="succeeded")continue;let c=s.outcome?.output;if(!c||typeof c!="object"||Array.isArray(c))throw new Error("Native SDK Supervisor cleanup has an invalid Child receipt");let l=c;if(typeof l.child!="string"||typeof l.worktree!="string"||Ke(l,e)!==r.children_contract_ref||!ye(l.worktree,zt(t,r.name,l.child))||l.branch!==`comet/supervisor/${r.name}/${l.child}`)throw new Error("Native SDK Supervisor cleanup has a mismatched Child receipt");a.set(l.child,{root:l.worktree,branch:l.branch})}if(a.size===0)throw new Error("Native SDK Supervisor cleanup has no prepared Children");return[...a.values(),{root:i,branch:o}]}function hW(e,t,r){let n=M(e.state),i=jS(e,"supervisor.parent.deliver");if(t.stepId!=="supervisor.cleanup"||n.status!=="done"||!n.archived||!n.children_contract_ref||!jS(e,"archive.finalize")||!i||typeof i.targetRoot!="string"||typeof i.targetBranch!="string"||typeof i.targetCommit!="string"||i.targetCommit!==i.integrationCommit||!Yt(r).some(o=>ye(o,i.targetRoot))||ue(i.targetRoot).currentBranch!==i.targetBranch||pe(i.targetRoot,i.targetBranch)!==i.targetCommit)throw new Error("Native SDK Supervisor cleanup lacks the verified delivery");return{projectRoot:r,targetRoot:i.targetRoot,targetBranch:i.targetBranch,targetCommit:i.targetCommit,candidates:mW(e,r,n)}}function gW(e,t,r,n){Hd({projectRoot:t,targetRoot:It(t,n.name),targetBranch:Nt(n.name),targetCommit:r,candidates:mW(e,t,n)})}function m5(e){return{targetBranch:e.targetBranch,targetCommit:e.targetCommit}}var $S,Wv,DS=x(()=>{"use strict";Cr();it();Se();Hs();rn();$S={id:"native-supervisor-cleanup",capabilities:[],supports(e){return e.stepId==="supervisor.cleanup"&&e.type==="call_tool"},async execute(e,t,r){if(!t?.projectRoot||!r||!this.supports(e))throw new Error("Native SDK Supervisor cleanup requires a bound Run and project");let n=hW(r,e,t.projectRoot);return await pR(n),{status:"succeeded",output:m5(n)}}},Wv={id:"native-supervisor-cleanup-outcome",version:"1",validate({run:e,action:t,outcome:r,context:n}){if(!n?.projectRoot||t.claim?.executorId!==$S.id||r.status!=="succeeded")return{accepted:!1,reason:"Native SDK Supervisor cleanup was not executed by Runtime"};try{let i=hW(e,t,n.projectRoot),o=r.output;if(!o||o.targetBranch!==i.targetBranch||o.targetCommit!==i.targetCommit||!rl(i))throw new Error("Native SDK Supervisor cleanup outcome does not match the worktrees");return{accepted:!0}}catch(i){return{accepted:!1,reason:i instanceof Error?i.message:String(i)}}}}});function Bl(e,t=e.outcome){let r=e.input.activation,i=t?.output?.candidateCommit??r?.integrationCommit;if(e.stepId!=="supervisor.parent.builder"||typeof r?.integrationCommit!="string"||!vW.test(r.integrationCommit)||typeof i!="string"||!vW.test(i))throw new Error("Native Supervisor parent candidate has no valid Git commit");return i}var vW,BS=x(()=>{"use strict";vW=/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u});import wW from"node:path";async function yW(e,t,r){let n=await Rn(e,r),i=M(e.state),o=t.input.activation,a=e.outputs["supervisor.prepare"]?.value,s=[...e.actions].reverse().find(v=>v.stepId==="supervisor.parent.builder"&&v.status==="succeeded"),c=s?Bl(s):null,l=e.waits.some(v=>v.stepId==="verify.confirm"&&v.status==="resolved"&&v.decision?.choice==="approved"),u=e.workflow.version==="4"||e.actions.some(v=>v.stepId==="verify.revalidate"&&v.status==="succeeded"),f=Nt(i.name),d=It(r,i.name);if(i.phase!=="archive"||i.verification_result!=="pass"||!i.verification||!i.builder_handoff||!l||!u||!o||Ke(o,e)!==i.children_contract_ref||o.candidateId!==i.builder_handoff.candidate_id||o.integrationBranch!==f||typeof o.integrationWorktree!="string"||!ye(o.integrationWorktree,d)||typeof o.integrationCommit!="string"||c!==o.integrationCommit||a?.targetBranch!==n.targetBranch||typeof a.targetCommit!="string"||ue(d).currentBranch!==f||pe(d,f)!==o.integrationCommit)throw new Error("Native SDK Supervisor delivery lacks the approved integration candidate");let p=Yt(r).find(v=>ue(v).currentBranch===n.targetBranch);if(!p)throw new Error("Native SDK Supervisor target branch worktree is unavailable");let m=pe(p,n.targetBranch),g=[...ur(e)].reverse().find(v=>v.stepId==="supervisor.child.integrate"&&v.status==="succeeded")?.outcome?.output?.targetCommit??a.targetCommit;if(m!==g&&m!==o.integrationCommit)throw new Error("Native SDK Supervisor target branch changed after Shape confirmation");return te(d,["merge-base","--is-ancestor",a.targetCommit,o.integrationCommit]),gW(e,r,o.integrationCommit,i),{state:i,input:o,targetRoot:p,targetBranch:n.targetBranch,targetCommit:m,integrationBranch:f,integrationCommit:o.integrationCommit}}function h5(e){return{contractRef:e.state.children_contract_ref,integrationCommit:e.integrationCommit,targetBranch:e.targetBranch,targetRoot:e.targetRoot,targetCommit:e.integrationCommit}}function g5(e,t){try{let r=e.targetRoot;te(r,["diff","--cached","--quiet",e.integrationCommit]),te(r,["diff","--quiet"]);let n=te(r,["diff","--name-only","--no-renames","-z",e.targetCommit,e.integrationCommit]).split("\0").filter(Boolean).map(o=>o.replaceAll("\\","/"));return te(r,["ls-files","--others","--exclude-standard","-z"]).split("\0").filter(Boolean).map(o=>o.replaceAll("\\","/")).some(o=>n.includes(o))?!1:ho(r,[...t,...n])}catch{return!1}}async function v5(e,t,r,n){let i=await we(n,t.input.artifactRootRef),o=ye(e.targetRoot,n)?wW.relative(e.targetRoot,wW.join(i.changesDir,e.state.name)).replaceAll("\\","/"):null,a=[...o?[o]:[],".comet/current-change.json",".comet/runtime"];if(!ho(e.targetRoot,a)&&!(e.targetCommit!==e.integrationCommit&&r.reconciliations.some(s=>s.attempt===r.attempt-1)&&g5(e,a)))throw new Error("Native SDK Supervisor target worktree has unrelated changes")}var WS,qv,kW=x(()=>{"use strict";DS();Cr();it();Sr();He();Se();BS();Hs();Qs();rn();el();WS={id:"native-supervisor-parent-deliver",capabilities:[],supports(e){return e.stepId==="supervisor.parent.deliver"&&e.type==="call_tool"},async execute(e,t,r){if(!t?.projectRoot||!r||!this.supports(e))throw new Error("Native SDK Supervisor delivery requires a bound Run and project");let n=await yW(r,e,t.projectRoot);if(await v5(n,r,e,t.projectRoot),n.targetCommit!==n.integrationCommit&&te(n.targetRoot,["merge","--ff-only",n.integrationBranch]),pe(n.targetRoot,n.targetBranch)!==n.integrationCommit)throw new Error("Native SDK Supervisor target did not receive the verified integration");return{status:"succeeded",output:h5(n)}}},qv={id:"native-supervisor-parent-deliver-outcome",version:"1",async validate({run:e,action:t,outcome:r,context:n}){if(!n?.projectRoot||t.claim?.executorId!==WS.id||r.status!=="succeeded")return{accepted:!1,reason:"Native SDK Supervisor delivery was not executed by Runtime"};try{let i=await yW(e,t,n.projectRoot),o=r.output;if(!o||Ke(o,e)!==i.state.children_contract_ref||o.integrationCommit!==i.integrationCommit||o.targetBranch!==i.targetBranch||typeof o.targetRoot!="string"||!ye(o.targetRoot,i.targetRoot)||o.targetCommit!==i.integrationCommit||pe(i.targetRoot,i.targetBranch)!==i.integrationCommit)throw new Error("Native SDK Supervisor delivery outcome does not match the target");return{accepted:!0}}catch(i){return{accepted:!1,reason:i instanceof Error?i.message:String(i)}}}}});async function AW(e,t,r){let n=await Rn(e,r),i=M(e.state),o=t.input.activation;if(i.phase!=="build"||!o||typeof o.child!="string"||!n.contract.children.some(({name:m})=>m===o.child)||Ke(o,e)!==i.children_contract_ref||typeof o.worktree!="string"||!ye(o.worktree,zt(r,i.name,o.child))||o.branch!==`comet/supervisor/${i.name}/${o.child}`||typeof o.candidateCommit!="string"||pe(o.worktree,o.branch)!==o.candidateCommit||typeof o.verifierActionId!="string"||typeof o.verifierSessionId!="string")throw new Error("Native SDK Supervisor integration lacks its verified Child candidate");let a=e.actions.find(m=>m.id===o.verifierActionId),s=a?.outcome?.output;if(a?.stepId!=="supervisor.child.verifier"||a.status!=="succeeded"||a.claim?.sessionId!==o.verifierSessionId||s?.verdict!=="pass"||s.candidateCommit!==o.candidateCommit)throw new Error("Native SDK Supervisor integration lacks a bound passing Verifier");let c=Nt(i.name),l=It(r,i.name);if(ue(l).currentBranch!==c)throw new Error("Native SDK Supervisor integration worktree changed");let u=e.actions.findIndex(m=>m.id===t.id),f=ur(e).filter(m=>e.actions.indexOf(m)<u).reverse().find(m=>["supervisor.child.integrate","supervisor.child.integration-repair"].includes(m.stepId)&&m.status==="succeeded"),d=e.outputs["supervisor.prepare"]?.value,p=f?f.outcome?.output?.integrationCommit:d?.integrationCommit??d?.targetCommit;if(typeof p!="string")throw new Error("Native SDK Supervisor integration lacks its checked base commit");return{state:i,plan:n,input:o,integrationBranch:c,integrationWorktree:l,expectedBaseCommit:p}}function RW(e,t,r){let n=t;for(let i of e.actions){if(i.stepId!=="supervisor.child.archive"||i.status!=="succeeded"||!i.outcome)continue;let o=i.outcome.output;o&&typeof o.baseCommit=="string"&&typeof o.integrationCommit=="string"&&o.baseCommit===n&&(n=o.integrationCommit)}return n===r}async function bW(e,t,r){let n=await AW(e,t,r);if(e.actions.some(a=>a.id!==t.id&&a.stepId==="supervisor.child.integrate"&&["running","unknown"].includes(a.status)))throw new Error("Another Native SDK Supervisor integration Action is unresolved");if(!Vo(n.integrationWorktree))throw new Error("Native SDK Supervisor integration worktree must be clean before merge");let i=pe(n.integrationWorktree,n.integrationBranch);if(!i||i!==n.expectedBaseCommit&&!RW(e,n.expectedBaseCommit,i))throw new Error("Native SDK Supervisor integration branch changed after the prior check");let o=e.outputs["supervisor.prepare"]?.value;if(typeof o?.targetCommit!="string")throw new Error("Native SDK Supervisor integration lacks its original target binding");return te(n.integrationWorktree,["merge-base","--is-ancestor",o.targetCommit,i]),te(n.integrationWorktree,["merge-base","--is-ancestor",o.targetCommit,n.plan.targetCommit]),{...n,baseCommit:i}}var Lv,qS,Vv,NW=x(()=>{"use strict";it();Sr();Cr();Se();Se();Hs();Qs();rn();Lv={id:"native-supervisor-integration-repair-outcome",version:"1",async validate({run:e,action:t,outcome:r,context:n}){if(r.status==="failed")return{accepted:!0};try{if(!n?.projectRoot||!t.claim?.sessionId)throw new Error("Integration repair requires its actual Agent session");let i=await Rn(e,n.projectRoot),o=t.input.activation,a=r.output,s=e.actions.find(y=>y.id===o?.mergeActionId),c=s?.outcome?.output,l=e.actions.find(y=>y.id===o?.failedCheckActionId),u=e.actions.find(y=>y.id===o?.failedExtensionActionId),f=u?.input?.activation?.reviewSource,d=e.actions.find(y=>y.id===o?.repairActionId),p=d?.outcome?.output,m=d?.status==="succeeded"&&d.stepId==="supervisor.child.integration-repair"&&d.input.activation?.mergeActionId===s?.id?p?.integrationCommit:c?.integrationCommit,h=l?.status==="failed"&&l.stepId==="supervisor.child.integration-checks"&&l.input.activation?.mergeActionId===s?.id,g=u?.stepId.startsWith("native.extension.integration.")&&u.outcome&&u.outcome.output.verdict==="fail"&&f?.scope==="integration"&&(f.actionId===s?.id||f.actionId===o?.repairActionId),v=It(n.projectRoot,i.state.name),w=Nt(i.state.name);if(!o||!h&&!g||Ke(o,e)!==i.state.children_contract_ref||typeof o.child!="string"||!i.contract.children.some(y=>y.name===o.child)||s?.stepId!=="supervisor.child.integrate"||s.status!=="succeeded"||c?.child!==o.child||m!==o.integrationCommit||typeof o.integrationWorktree!="string"||!ye(o.integrationWorktree,v)||o.integrationBranch!==w||!a||typeof a.summary!="string"||!a.summary.trim()||typeof a.integrationCommit!="string"||typeof o.integrationCommit!="string"||a.integrationCommit===o.integrationCommit||ue(v).currentBranch!==w||pe(v,w)!==a.integrationCommit||!Vo(v))throw new Error("Integration repair does not match its original merge, failure and workspace");if(te(v,["merge-base","--is-ancestor",o.integrationCommit,a.integrationCommit]),Ti(a.checks??[]).some(y=>y.result==="failed"))throw new Error("Resolve failed platform checks before submitting integration repair");return{accepted:!0}}catch(i){return{accepted:!1,reason:i instanceof Error?i.message:String(i)}}}};qS={id:"native-supervisor-integrate",capabilities:[],supports(e){return e.stepId==="supervisor.child.integrate"&&e.type==="call_tool"},async preflight(e,t,r){if(!t?.projectRoot||!r||!this.supports(e))throw new Error("Native SDK Supervisor integration requires a bound Run and project");await bW(r,e,t.projectRoot)},async execute(e,t,r){if(!t?.projectRoot||!r||!this.supports(e))throw new Error("Native SDK Supervisor integration requires a bound Run and project");let n=await bW(r,e,t.projectRoot),{baseCommit:i}=n;te(n.integrationWorktree,["merge-base",n.plan.targetCommit,i])===n.plan.targetCommit||te(n.integrationWorktree,["merge","--no-ff","--no-edit",n.plan.targetCommit]);let a=pe(n.integrationWorktree,n.integrationBranch);if(!a)throw new Error("Native SDK Supervisor target sync produced no commit");te(n.integrationWorktree,["merge-base",n.input.candidateCommit,a])===n.input.candidateCommit||te(n.integrationWorktree,["merge","--no-ff","--no-edit",n.input.candidateCommit]);let c=pe(n.integrationWorktree,n.integrationBranch);if(!c)throw new Error("Native SDK Supervisor merge produced no commit");return{status:"succeeded",output:{child:n.input.child,candidateCommit:n.input.candidateCommit,baseCommit:i,targetCommit:n.plan.targetCommit,targetMergeCommit:a,integrationCommit:c,integrationBranch:n.integrationBranch,integrationWorktree:n.integrationWorktree}}}},Vv={id:"native-supervisor-integrate-outcome",version:"1",async validate({run:e,action:t,outcome:r,context:n}){if(!n?.projectRoot||t.claim?.executorId!==qS.id||r.status!=="succeeded")return{accepted:!1,reason:"Native SDK Supervisor integration was not executed by Runtime"};try{let i=await AW(e,t,n.projectRoot),o=r.output;if(!o||o.child!==i.input.child||o.candidateCommit!==i.input.candidateCommit||o.baseCommit!==i.expectedBaseCommit&&(typeof o.baseCommit!="string"||!RW(e,i.expectedBaseCommit,o.baseCommit))||typeof o.integrationCommit!="string"||o.integrationBranch!==i.integrationBranch||typeof o.integrationWorktree!="string"||!ye(o.integrationWorktree,i.integrationWorktree)||pe(i.integrationWorktree,i.integrationBranch)!==o.integrationCommit)throw new Error("Native SDK Supervisor integration outcome does not match the worktree");if(!Vo(i.integrationWorktree))throw new Error("Native SDK Supervisor integration worktree changed after execution");let a=e.outputs["supervisor.prepare"]?.value,s=o.targetCommit??a.targetCommit,c=o.targetMergeCommit??o.baseCommit;if(s!==i.plan.targetCommit||typeof c!="string")throw new Error("Native SDK Supervisor target changed during integration");if(c!==o.baseCommit){let l=te(i.integrationWorktree,["rev-list","--parents","-n","1",c]).split(" ");if(l.length!==3||l[0]!==c||l[1]!==o.baseCommit||l[2]!==s)throw new Error("Native SDK Supervisor target sync is not the expected merge commit")}if(te(i.integrationWorktree,["merge-base","--is-ancestor",s,c]),o.integrationCommit===c)te(i.integrationWorktree,["merge-base","--is-ancestor",o.candidateCommit,o.integrationCommit]);else{let l=te(i.integrationWorktree,["rev-list","--parents","-n","1",o.integrationCommit]).split(" ");if(l.length!==3||l[0]!==o.integrationCommit||l[1]!==c||l[2]!==o.candidateCommit)throw new Error("Native SDK Supervisor integration is not the expected merge commit")}return{accepted:!0}}catch(i){return{accepted:!1,reason:i instanceof Error?i.message:String(i)}}}}});function Mv(e,t){let r=M(e.state),n=t.input.activation;if(r.phase!=="build"||r.archived||!r.children_contract_ref||t.stepId!=="supervisor.child.verifier"||t.status!=="failed"||t.outcome?.status!=="failed"||!t.claim||!n||Ke(n,e)!==r.children_contract_ref||typeof n.child!="string"||typeof n.candidateCommit!="string"||typeof n.builderSessionId!="string"||!ur(e).some(i=>i.id===t.id))throw new Error("Native Child Verifier recovery requires a known failed current execution");return{...n,failedVerifierActionId:t.id}}function SW(e){return e.waits.filter(t=>{if(t.status!=="pending"||t.stepId!=="supervisor.child.verifier-retry")return!1;let r=t.proposal.activation;if(LS(e,t))return!0;let n=e.actions.find(i=>i.id===r?.failedVerifierActionId);return n!==void 0&&D(Mv(e,n))===D(r)})}function LS(e,t){return e.actions.find(r=>["supervisor.child.checks","supervisor.child.integration-checks"].includes(r.stepId)&&r.status==="failed"&&r.outcome?.status==="failed"&&r.executionOrigin&&["1","2","3"].includes(r.executionOrigin.workflow.version)&&e.actionContexts[r.id].sequence===t.results[r.stepId]?.sequence)}var VS=x(()=>{"use strict";ze();Cr();Se();Hs();Qs()});var TW={};fw(TW,{assertNativeSdkStartAvailable:()=>GS,collectNativeSdkShapeProposal:()=>y5,defineNativeWorkflowApplication:()=>Wl,nativeSdkApplicationForRun:()=>KS,registerNativeSdkStartOwner:()=>w5});import xW from"node:path";function KS(e,t=Wl()){if(e&&(e.workflow.version!=="4"||!wv(t.workflow,e)))throw new Error("Native Run 尚未完成业务数据适配,请通过原 change 的当前入口继续;原记录与批准保留。");return t}async function GS(e){let t=await we(e.projectRoot,e.artifactRootRef,{change:e.name});if((await ie(e.projectRoot,xW.relative(e.projectRoot,Pt(t,e.name)),{label:"Native legacy change state",expected:"file"})).exists)throw new Error(`Native change ${e.name} already has legacy Runtime state`)}async function w5(e){let t=await we(e.projectRoot,e.artifactRootRef,{change:e.name});await $e(t,async()=>{await GS(e),await Ro(e.projectRoot,{schema:pi,workflow:"native",change:e.name,format:"sdk",application:"native",runId:e.name})})}function PW(e){return e.phase==="shape"&&e.status==="active"&&e.loop.next_action==="prepare-shape-confirmation"?3:e.document_constraints_version??2}async function y5(e){let t=M({...e.state,document_constraints_version:PW(e.state)});if(t.phase!=="shape"||!["active","await-user"].includes(t.status))throw new Error("Native Shape proposal requires an active or pending Shape");let r=xW.join(e.paths.changesDir,t.name),n=await cv({paths:e.paths,state:t});e.materializeTargets===!0&&t.status==="active"&&t.shape_confirmation_hash===void 0&&n.some(s=>s.delta_source)&&await $e(e.paths,()=>tS({paths:e.paths,state:t,specChanges:n}));let i=t.status==="active"&&t.loop.next_action==="prepare-shape-confirmation"&&t.shape_confirmation_hash===void 0;await nS({paths:e.paths,state:i?{...t,spec_changes:n}:t,specChanges:n});let o=e.acceptance===void 0?(await lv({paths:e.paths,state:t,specChanges:n})).acceptance:e.acceptance.map((s,c)=>{let l=["brief.md",...n.flatMap(f=>f.source?[f.source]:[])];if(!s||typeof s.source!="string"||typeof s.text!="string"||!s.text.trim())throw new Error("Native acceptance requires a readable source reference and nonempty text");let u=Jo(s.source,"Native acceptance source");if(!l.includes(u))throw new Error("Native acceptance must reference this change brief or a declared specification");return{id:`A${c+1}`,source:u,text:s.text.trim()}});if(!o.length)throw new Error("Native Shape requires at least one acceptance criterion");let a=await pn({changeDir:r,acceptanceIds:o.map(({id:s})=>s),validation:fn({...t,acceptance:o})});return{specChanges:n,acceptance:o.map(({id:s,source:c,text:l})=>({id:s,source:c,text:l})),children:a?{contract:a.contract}:null}}function MS(e){let t={...e,status:"active",state_version:e.state_version+1,loop:{...e.loop,stage:"shape",next_action:"prepare-shape-confirmation"},acceptance:[]};return delete t.shape_confirmation_hash,delete t.children_contract_ref,delete t.children_contract,delete t.coordination_mode,M(t)}function k5(e,t){let r={...e,phase:"shape",status:"active",state_version:e.state_version+1,spec_changes:t,acceptance:[],builder_handoff:null,blockers:[],verification:null,verification_result:"pending",verification_report:null,history:[],history_overflow:Uc(),loop:{stage:"shape",goal_cycle:e.loop.goal_cycle+(e.phase==="shape"?0:1),iteration:0,attempt:0,retry_epoch:0,failed_iteration_count:0,no_progress_count:0,execution_failure_count:0,previous_unresolved_ids:[],next_action:"prepare-shape-confirmation"}};return delete r.shape_confirmation_hash,delete r.children_contract_ref,delete r.children_contract,delete r.coordination_mode,delete r.verifier_action,M(r)}function EW(e,t){let n={...vn(e,{goal_cycle:e.loop.goal_cycle,iteration:e.loop.iteration,attempt:e.loop.attempt,outcome:"recovery",unresolved_ids:[],summary:Ct(t),completed_at:new Date().toISOString()}),phase:"shape",status:"active",state_version:e.state_version+1,acceptance:[],builder_handoff:null,blockers:[],verification:null,verification_result:"pending",verification_report:null,loop:{stage:"shape",goal_cycle:e.loop.goal_cycle+1,iteration:0,attempt:0,retry_epoch:0,failed_iteration_count:0,no_progress_count:0,execution_failure_count:0,previous_unresolved_ids:[],next_action:"prepare-shape-confirmation"}};return delete n.shape_confirmation_hash,delete n.children_contract_ref,delete n.children_contract,delete n.coordination_mode,delete n.verifier_action,M(n)}function Js(e){if(e===null||typeof e!="object")throw new Error("Native Shape proposal missing");return e}function CW(e,t,r=!1){let n=e.input.activation,i=t;if(!n||!e.claim?.sessionId||!r&&!i?.integrationChecks)throw new Error("Native SDK Supervisor Verifier lacks its Child activation");return{...n,verifierActionId:e.id,verifierSessionId:e.claim.sessionId,...r?{}:{integrationChecks:i.integrationChecks}}}function b5(e){let t=ur(e),r=new Set(t.filter(n=>n.stepId==="supervisor.child.integrate").map(n=>n.input.activation?.child));return t.find(n=>n.stepId==="supervisor.child.verifier"&&n.status==="succeeded"&&n.outcome?.output?.verdict==="pass"&&!r.has(n.input.activation?.child))??null}function FS(e,t,r){let n=t.input.activation,o=ur(e).find(a=>a.stepId==="supervisor.child.builder"&&a.status==="succeeded"&&a.claim?.sessionId===n?.builderSessionId&&a.outcome?.output?.candidateCommit===n?.candidateCommit)?.input?.activation;if(!o||o.child!==n?.child)throw new Error("Native SDK Supervisor repair lacks the failed Child Builder");return{...o,[r]:t.id}}function Fv(e,t){let r=[...ur(e)].reverse().find(i=>i.stepId==="supervisor.parent.builder"&&i.status==="succeeded"),n=r?.input?.activation;if(!r||!n)throw new Error("Native Supervisor parent repair lacks the prior integration candidate");return{...n,integrationCommit:Bl(r),...t}}function _W(e,t,r){let n=r.output,i=t.claim?.sessionId;if(["3","4"].includes(e.workflow.version)&&n?.requireIndependentReview!==void 0&&typeof n.requireIndependentReview!="boolean")throw new Error("requireIndependentReview must be a boolean");let o=M(e.state);if(o.phase!=="build"||!["build.builder","supervisor.parent.builder"].includes(t.stepId)||t.type!=="handoff"||!i||!n||typeof n.summary!="string"||!n.summary.trim()||n.addressedAcceptanceIds!==void 0&&(!Array.isArray(n.addressedAcceptanceIds)||n.addressedAcceptanceIds.some(l=>typeof l!="string"))||!Array.isArray(n.checks)||!Array.isArray(n.knownLimits)||n.knownLimits.some(l=>typeof l!="string"))throw new Error("Native Builder result needs a claimed host session and a complete candidate");let a=n.checks,s=n.review;if(s!=null&&(s.status!=="passed"||typeof s.summary!="string"||typeof s.reviewerExecutionRef!="string"))throw new Error("Native Builder review is invalid");let c=rR().captureExecutionIdentity({identityProvider:$r,executionRef:i});return KN({state:o,requireAcceptanceReview:!["3","4"].includes(e.workflow.version),input:{identity:c,summary:n.summary,addressedAcceptanceIds:n.addressedAcceptanceIds??[],acceptanceReview:n.acceptanceReview===void 0?void 0:n.acceptanceReview,checks:a,knownLimits:n.knownLimits,review:s?{status:"passed",summary:s.summary,reviewerExecutionRef:s.reviewerExecutionRef}:null,candidateId:t.id,now:typeof n.submittedAt=="string"&&!Number.isNaN(Date.parse(n.submittedAt))?new Date(n.submittedAt):new Date}})}function A5(e,t,r){let n=r.output,i=t.claim?.sessionId,o=M(e.state),a=o.builder_handoff;if(o.phase!=="verify"||o.status!=="active"||o.loop.next_action!=="await-verifier-result"||t.stepId!=="verify.verifier"||t.type!=="handoff"||r.status!=="succeeded"||!a||!i||zi(e,t)&&i===a.builder_execution_ref||!n||n.candidateId!==a.candidate_id||n.verifierExecutionRef!==i)throw new Error(`Native Verifier result is not bound to an independent current execution; candidateId must match the current candidate and verifierExecutionRef must equal the claimed sessionId ${i??"(missing)"}; use the current outcomeRequest template`);let c=e.input.maxVerifyFailures??xu;if(!Number.isSafeInteger(c)||c<1)throw new Error("Native Verify failure budget is invalid");let l=rR(),u=l.captureExecutionIdentity({identityProvider:$r,executionRef:i}),f=GN({state:o,requireIndependentSession:!1,envelope:l.envelopeVerifierResponse({candidateId:a.candidate_id,identity:u,payload:n.response}),reportedChecks:Ti(n.checks??[]),maxVerifyFailures:c});if(typeof e.input.task=="string"&&f.response.result.verdict==="pass"&&f.response.result.requestReview?.result!=="aligned")throw new Error("Native pass requires requestReview aligned with the original task and authorized changes; report fail or blocked for conflicts or unresolved requirements");return{state:f.state}}function R5(e,t,r){let n=r.output;if(r.status!=="failed"||t.stepId!=="verify.verifier"||t.type!=="handoff"||!t.claim?.sessionId||!n||typeof n.summary!="string"||!n.summary.trim())throw new Error("Native Verifier execution failure needs the original claimed session and summary");let i=M(e.state);return ZN({state:i,summary:n.summary})}function Wl(e="4"){if(e!=="4")throw new Error("旧 Native 受管检查定义不再支持;普通检查请使用 Agent 平台工具。");return S5()}function IW(e,t){let r=[...e.actions].reverse().find(o=>o.stepId==="shape.prepare"&&o.status==="succeeded"),n=Js(r.outcome.output),i=JN({state:t,acceptance:t.acceptance.map(({id:o,source:a,text:s})=>({id:o,source:a,text:s}))});return n.children?{state:M({...i,children_contract_ref:r.id,children_contract:n.children.contract}),next:["supervisor.prepare"]}:{state:i,next:["build.builder"]}}function N5(e,t){let r=YN(t);if(!r.children_contract_ref)return{state:r,next:["archive.prepare"]};let n=[...e.actions].reverse().find(o=>o.stepId==="supervisor.parent.builder"&&o.status==="succeeded"),i=n?.input?.activation;if(!n||!i)throw new Error("Native Supervisor delivery lacks its parent integration candidate");return{state:r,next:[{stepId:"supervisor.parent.deliver",input:{...i,integrationCommit:Bl(n),candidateId:r.builder_handoff?.candidate_id??null}}]}}function S5(){return{workflow:{id:"comet-native",version:"4",entry:"shape.prepare",commands:{"revise-implementation":{stepId:"repair.implementation",validator:{id:Ev.id,version:Ev.version}},"revise-requirements":{stepId:"shape.revise",validator:{id:Iv.id,version:Iv.version}},"remove-capability":{stepId:"shape.remove",validator:{id:Nv.id,version:Nv.version}},"disassociate-capability":{stepId:"shape.disassociate",validator:{id:bv.id,version:bv.version}}},stateSchema:{type:"object",required:["schema","name","phase","status","state_version","loop","acceptance"],properties:{schema:{const:"comet.native.v4"},name:{type:"string"},phase:{enum:["shape","build","verify","archive"]},status:{enum:["active","await-user","blocked","done"]},state_version:{type:"integer",minimum:1},loop:{type:"object"},acceptance:{type:"array"}}},transitionHandler:{id:"comet-native-transition",version:"1"},stateValidator:{id:zS.id,version:zS.version},steps:{"repair.implementation":{type:"call_tool",ref:"native-revise-implementation",validator:{id:Cv.id,version:Cv.version}},"shape.revise":{type:"call_tool",ref:"native-revise-requirements",validator:{id:xv.id,version:xv.version}},"shape.remove":{type:"call_tool",ref:"native-remove",validator:{id:Sv.id,version:Sv.version}},"shape.disassociate":{type:"call_tool",ref:"native-disassociate",validator:{id:Av.id,version:Av.version}},"shape.prepare":{type:"call_tool",ref:"native-shape-prepare",validator:{id:HS.id,version:HS.version}},"shape.confirm":{type:"ask_user",proposalFrom:"shape.prepare",choices:["approved","rejected"]},"supervisor.shape.confirm":{type:"ask_user",proposalFrom:"shape.prepare",choices:["multi-session","single-session","rejected"]},"build.builder":{type:"handoff",ref:"native-builder",validator:{id:QS.id,version:QS.version}},"build.resume":{type:"ask_user",proposalFrom:"build.builder",choices:["continue"]},"supervisor.prepare":{type:"call_tool",ref:"native-supervisor-prepare",validator:{id:Pv.id,version:Pv.version}},"supervisor.child.prepare":{type:"call_tool",ref:"native-supervisor-child-prepare",validator:{id:Tv.id,version:Tv.version}},"supervisor.child.builder":{type:"handoff",ref:"native-supervisor-builder",validator:{id:Dv.id,version:Dv.version}},"supervisor.child.resume":{type:"ask_user",proposalFrom:"supervisor.child.builder",choices:["continue"]},"supervisor.child.verifier":{type:"handoff",ref:"native-supervisor-verifier",validator:{id:Bv.id,version:Bv.version}},"supervisor.child.verifier-retry":{type:"ask_user",proposalFrom:"supervisor.child.verifier",choices:["retry","repair"]},"supervisor.child.integrate":{type:"call_tool",ref:"native-supervisor-integrate",validator:{id:Vv.id,version:Vv.version}},"supervisor.child.integration-repair":{type:"handoff",ref:"native-supervisor-integration-repair",validator:{id:Lv.id,version:Lv.version}},"supervisor.child.integration-resume":{type:"ask_user",proposalFrom:"supervisor.child.integration-repair",choices:["continue"]},"supervisor.child.archive":{type:"call_tool",ref:"native-supervisor-child-archive",validator:{id:$v.id,version:$v.version}},"supervisor.parent.builder":{type:"handoff",ref:"native-supervisor-parent-builder",validator:{id:US.id,version:US.version}},"supervisor.parent.resume":{type:"ask_user",proposalFrom:"supervisor.parent.builder",choices:["continue"]},"supervisor.parent.deliver":{type:"call_tool",ref:"native-supervisor-parent-deliver",validator:{id:qv.id,version:qv.version}},"supervisor.cleanup":{type:"call_tool",ref:"native-supervisor-cleanup",validator:{id:Wv.id,version:Wv.version}},"verify.verifier":{type:"handoff",ref:"native-verifier",validator:{id:JS.id,version:JS.version}},"verify.retry":{type:"ask_user",proposalFrom:"verify.verifier",choices:["retry"]},"verify.stop":{type:"ask_user",proposalFrom:"verify.verifier",choices:["retry","repair"]},"verify.confirm":{type:"ask_user",proposalFrom:"verify.verifier",choices:["approved","rejected","reverify"]},"archive.prepare":{type:"call_tool",ref:"native-archive-preflight",retry:"idempotent",validator:{id:mv.id,version:mv.version}},"archive.execute":{type:"call_tool",ref:"native-archive",validator:{id:hv.id,version:hv.version}},"archive.finalize":{type:"call_tool",ref:"native-archive-finalize",validator:{id:gv.id,version:gv.version}}},transitions:[{from:"repair.implementation",to:"archive.prepare"},{from:"repair.implementation",to:"archive.execute"},{from:"repair.implementation",to:"shape.prepare"},{from:"repair.implementation",to:"build.builder"},{from:"repair.implementation",to:"supervisor.parent.builder"},{from:"shape.revise",to:"shape.prepare"},{from:"shape.remove",to:"shape.prepare"},{from:"shape.disassociate",to:"shape.prepare"},{from:"shape.prepare",to:"shape.confirm"},{from:"shape.prepare",to:"supervisor.shape.confirm"},{from:"shape.confirm",to:"shape.prepare",on:"rejected"},{from:"supervisor.shape.confirm",to:"shape.prepare",on:"rejected"},{from:"supervisor.prepare",to:"supervisor.child.prepare"},{from:"supervisor.child.prepare",to:"supervisor.child.builder"},{from:"supervisor.child.builder",to:"supervisor.child.resume",on:"failed"},{from:"supervisor.child.resume",to:"supervisor.child.builder",on:"continue"},{from:"supervisor.child.verifier",to:"supervisor.child.verifier-retry",on:"failed"},{from:"supervisor.child.verifier-retry",to:"supervisor.child.verifier",on:"retry"},{from:"supervisor.child.verifier-retry",to:"supervisor.child.builder",on:"repair"},{from:"supervisor.child.verifier",to:"supervisor.child.integrate"},{from:"supervisor.child.verifier",to:"supervisor.child.builder"},{from:"supervisor.child.archive",to:"supervisor.child.integrate"},{from:"supervisor.child.archive",to:"supervisor.child.prepare"},{from:"supervisor.child.archive",to:"supervisor.parent.builder"},{from:"supervisor.parent.builder",to:"supervisor.parent.resume",on:"failed"},{from:"supervisor.parent.resume",to:"supervisor.parent.builder",on:"continue"},{from:"build.builder",to:"build.resume",on:"failed"},{from:"build.resume",to:"build.builder",on:"continue"},{from:"verify.verifier",to:"verify.confirm"},{from:"verify.verifier",to:"build.builder"},{from:"verify.verifier",to:"supervisor.parent.builder"},{from:"verify.verifier",to:"verify.verifier",on:"failed"},{from:"verify.verifier",to:"verify.retry",on:"failed"},{from:"verify.retry",to:"verify.verifier",on:"retry"},{from:"verify.verifier",to:"verify.stop"},{from:"verify.stop",to:"verify.verifier",on:"retry"},{from:"verify.stop",to:"build.builder",on:"repair"},{from:"verify.stop",to:"supervisor.parent.builder",on:"repair"},{from:"verify.confirm",to:"archive.prepare",on:"approved"},{from:"verify.confirm",to:"build.builder",on:"rejected"},{from:"verify.confirm",to:"supervisor.parent.builder",on:"rejected"},{from:"supervisor.parent.deliver",to:"archive.prepare"},{from:"archive.prepare",to:"archive.execute"},{from:"archive.prepare",to:"verify.stop",on:"failed"},{from:"archive.execute",to:"verify.stop",on:"failed"},{from:"archive.execute",to:"archive.finalize"},{from:"archive.finalize",to:"supervisor.cleanup"},{from:"verify.confirm",to:"verify.verifier",on:"reverify"},{from:"build.builder",to:"verify.verifier"},{from:"supervisor.parent.builder",to:"verify.verifier"},{from:"supervisor.child.builder",to:"supervisor.child.verifier"},{from:"supervisor.child.integrate",to:"supervisor.child.archive"},{from:"supervisor.child.verifier-retry",to:"supervisor.child.integration-repair",on:"repair"},{from:"supervisor.child.integration-repair",to:"supervisor.child.archive"},{from:"supervisor.child.integration-repair",to:"supervisor.child.integration-resume",on:"failed"},{from:"supervisor.child.integration-resume",to:"supervisor.child.integration-repair",on:"continue"},{from:"shape.confirm",to:"build.builder",on:"approved"},{from:"shape.confirm",to:"supervisor.prepare",on:"approved"},{from:"supervisor.shape.confirm",to:"supervisor.prepare",on:"multi-session"},{from:"supervisor.shape.confirm",to:"supervisor.prepare",on:"single-session"},{from:"verify.confirm",to:"supervisor.parent.deliver",on:"approved"}]},transitionHandler:{id:"comet-native-transition",version:"1",apply({run:t,event:r}){let n=M(t.state);if(r.kind==="action-outcome"&&r.stepId==="repair.implementation"){if(r.outcome.status!=="succeeded")return{state:n,next:[]};let i=r.outcome.output;if(!i.drift)return{state:n,next:[i.archiveStep]};if(i.requirementsChanged)return{state:EW(n,i.reason),next:["shape.prepare"]};let o=xl({state:n,reason:i.reason}),a=[...t.actions].reverse().find(s=>s.stepId==="verify.verifier"&&s.status==="succeeded");if(!a)throw new Error("Native implementation revision has no original Verifier result");return{state:o,next:n.children_contract_ref?[{stepId:"supervisor.parent.builder",input:Fv(t,{failedVerifierActionId:a.id})}]:[{stepId:"build.builder",input:{repairContext:Dd(o,t)}}]}}if(r.kind==="action-outcome"&&r.stepId==="shape.revise"){if(r.outcome.status!=="succeeded")return{state:n,next:[]};let i=r.outcome.output.reason;return{state:EW(n,i),next:["shape.prepare"]}}if(r.kind==="action-outcome"&&r.stepId==="shape.remove"){if(r.outcome.status!=="succeeded")return{state:n,next:[]};let i=r.outcome.output.capability,o=[...n.spec_changes.filter(a=>a.capability!==i),{capability:i,operation:"remove",source:null}].sort((a,s)=>a.capability.localeCompare(s.capability,"en"));return{state:k5(n,o),next:["shape.prepare"]}}if(r.kind==="action-outcome"&&r.stepId==="shape.disassociate")return r.outcome.status!=="succeeded"?{state:n,next:[]}:{state:MS(n),next:["shape.prepare"]};if(r.kind==="action-outcome"&&r.stepId==="shape.prepare"){if(r.outcome.status!=="succeeded")return{state:n,next:[]};let i=Js(r.outcome.output);return{state:zN({state:{...n,document_constraints_version:PW(n),spec_changes:i.specChanges},acceptance:i.acceptance}),next:i.children&&i.children.contract.children.length>=2?["supervisor.shape.confirm"]:["shape.confirm"]}}if(r.kind==="wait-resolved"&&r.stepId==="shape.confirm")return r.choice==="approved"?IW(t,n):{state:MS(n),next:["shape.prepare"]};if(r.kind==="wait-resolved"&&r.stepId==="supervisor.shape.confirm"){if(r.choice==="rejected")return{state:MS(n),next:["shape.prepare"]};let i=Js(t.outputs["shape.prepare"]?.value);if(!i.children||i.children.contract.children.length<2)throw new Error("Native Supervisor approval lacks its child plan");let o=r.choice,a=M({...n,coordination_mode:o});return IW(t,a)}if(r.kind==="action-outcome"&&r.stepId==="supervisor.prepare"){if(r.outcome.status!=="succeeded")return{state:n,next:[]};let i=Js(t.actions.find(s=>s.id===n.children_contract_ref)?.outcome?.output);if(!i.children||!n.children_contract_ref)throw new Error("Native Supervisor preparation lacks the confirmed child plan");let o=r.outcome.output,a=CS({contract:i.children.contract,integrated:[],active:[],maxParallel:n.coordination_mode==="single-session"?1:o.maxParallelChildren??2});return{state:n,next:a.map(s=>({stepId:"supervisor.child.prepare",input:{child:s,contractRef:n.children_contract_ref,integrationBranch:o.integrationBranch,integrationWorktree:o.integrationWorktree,targetCommit:o.integrationCommit??o.targetCommit}}))}}if(r.kind==="action-outcome"&&r.stepId==="supervisor.child.prepare"){if(r.outcome.status!=="succeeded")return{state:n,next:[]};let i=r.outcome.output;return{state:n,next:[{stepId:"supervisor.child.builder",input:i}]}}if(r.kind==="action-outcome"&&r.stepId==="supervisor.child.builder"){if(r.outcome.status!=="succeeded"){let s=t.actions.find(l=>l.id===r.outcome.actionId),c=s?.input?.activation;if(!c||!s)throw new Error("Native SDK Supervisor Child Builder failure lacks its Action");return{state:n,next:[{stepId:"supervisor.child.resume",input:{...c,failedBuilderActionId:s.id}}]}}let i=t.actions.find(s=>s.id===r.outcome.actionId);if(!i?.claim?.sessionId)throw new Error("Native SDK Supervisor Builder Action lacks its host session");let o=i.input.activation,a=Js(t.actions.find(s=>s.id===n.children_contract_ref)?.outcome?.output);if(!o||!a.children||typeof o.child!="string")throw new Error("Native SDK Supervisor Builder lacks its confirmed child plan");return{state:n,next:[{stepId:"supervisor.child.verifier",input:{...o,candidateCommit:r.outcome.output.candidateCommit,builderSessionId:i.claim.sessionId,acceptance:oi(a.children.contract,o.child),checks:r.outcome.output.checks??[]}}]}}if(r.kind==="wait-resolved"&&r.stepId==="supervisor.child.resume"){let o=t.waits.find(a=>a.stepId==="supervisor.child.resume"&&a.decision?.id===r.decisionId&&a.proposalHash===r.proposalHash)?.proposal?.activation;if(!o||typeof o.failedBuilderActionId!="string"||!t.actions.some(a=>a.id===o.failedBuilderActionId&&a.stepId==="supervisor.child.builder"&&a.status==="failed"))throw new Error("Native SDK Supervisor Child continuation lacks its failed Action");return{state:n,next:[{stepId:"supervisor.child.builder",input:o}]}}if(r.kind==="wait-resolved"&&r.stepId==="supervisor.child.verifier-retry"){let i=t.waits.find(c=>c.stepId===r.stepId&&c.decision?.id===r.decisionId&&c.proposalHash===r.proposalHash),o=i?.proposal?.activation,a=i&&LS(t,i);if(a){if(r.choice!=="repair")throw new Error("旧失败提案只允许原 repair 决定");let c=a.input.activation;return{state:n,next:[{stepId:a.stepId==="supervisor.child.integration-checks"?"supervisor.child.integration-repair":"supervisor.child.builder",input:a.stepId==="supervisor.child.integration-checks"?{...c,contractRef:n.children_contract_ref,failedCheckActionId:a.id}:FS(t,a,"failedCheckActionId")}]}}let s=t.actions.find(c=>c.id===o?.failedVerifierActionId);if(!s||!o||D(Mv(t,s))!==D(o))throw new Error("Native Child Verifier recovery lacks its original failed Action");return{state:n,next:[{stepId:r.choice==="retry"?"supervisor.child.verifier":"supervisor.child.builder",input:r.choice==="retry"?o:FS(t,s,"failedVerifierActionId")}]}}if(r.kind==="action-outcome"&&r.stepId==="supervisor.child.verifier"){if(r.outcome.status!=="succeeded"){let a=t.actions.find(s=>s.id===r.outcome.actionId);if(!a)throw new Error("Native SDK Supervisor Verifier Action is missing");return{state:n,next:[{stepId:"supervisor.child.verifier-retry",input:Mv(t,a)}]}}let i=r.outcome.output;if(i.verdict==="fail"||i.verdict==="blocked"){let a=t.actions.find(s=>s.id===r.outcome.actionId);if(!a)throw new Error("Native SDK Supervisor Verifier Action is missing");return{state:n,next:[{stepId:"supervisor.child.builder",input:FS(t,a,"failedVerifierActionId")}]}}if(i.verdict!=="pass")return{state:n,next:[]};if(t.actions.some(a=>["supervisor.child.integrate","supervisor.child.integration-repair"].includes(a.stepId)&&["pending","running","unknown"].includes(a.status)))return{state:n,next:[]};let o=t.actions.find(a=>a.id===r.outcome.actionId);if(!o)throw new Error("Native SDK Supervisor Verifier Action is missing");return{state:n,next:[{stepId:"supervisor.child.integrate",input:CW(o,r.outcome.output,t.workflow.version==="4")}]}}if(r.kind==="action-outcome"&&r.stepId==="supervisor.child.integrate"){if(r.outcome.status!=="succeeded")return{state:n,next:[]};let o=t.actions.find(s=>s.id===r.outcome.actionId)?.input?.activation,a=r.outcome.output;if(!o)throw new Error("Native SDK Supervisor integration lacks its Child activation");return{state:n,next:[{stepId:"supervisor.child.archive",input:{child:o.child,candidateCommit:o.candidateCommit,integrationCommit:a.integrationCommit,mergeActionId:r.outcome.actionId,contractRef:n.children_contract_ref}}]}}if(r.kind==="action-outcome"&&r.stepId==="supervisor.child.integration-repair"){let i=t.actions.find(a=>a.id===r.outcome.actionId),o=i.input.activation;return{state:n,next:[{stepId:r.outcome.status==="failed"?"supervisor.child.integration-resume":"supervisor.child.archive",input:r.outcome.status==="failed"?{...o,failedBuilderActionId:i.id}:{...o,integrationCommit:r.outcome.output.integrationCommit,repairActionId:i.id}}]}}if(r.kind==="wait-resolved"&&r.stepId==="supervisor.child.integration-resume"){let o=t.waits.find(a=>a.stepId===r.stepId&&a.decision?.id===r.decisionId&&a.proposalHash===r.proposalHash).proposal.activation;if(!t.actions.some(a=>a.id===(o.failedRepairActionId??o.failedBuilderActionId)&&a.stepId==="supervisor.child.integration-repair"&&a.status==="failed"))throw new Error("Integration continuation lacks its original failed repair");return{state:n,next:[{stepId:"supervisor.child.integration-repair",input:o}]}}if(r.kind==="action-outcome"&&r.stepId==="supervisor.child.archive"){if(r.outcome.status!=="succeeded")return{state:n,next:[]};let i=Js(t.actions.find(d=>d.id===n.children_contract_ref)?.outcome?.output),o=t.outputs["supervisor.prepare"]?.value;if(!i.children||!n.children_contract_ref||!o)throw new Error("Native SDK Supervisor continuation lacks its confirmed plan");let a=new Set(ur(t).filter(d=>d.stepId==="supervisor.child.archive"&&d.status==="succeeded").map(d=>d.input.activation.child)),s=t.actions.find(d=>d.id===r.outcome.actionId);if(!s)throw new Error("Native SDK Supervisor archive Action missing");a.add(s.input.activation.child);let c=b5(t);if(c)return{state:n,next:[{stepId:"supervisor.child.integrate",input:CW(c,c.outcome?.output,t.workflow.version==="4")}]};let l=new Set(ur(t).filter(d=>d.stepId==="supervisor.child.prepare").map(d=>d.input.activation.child).filter(d=>!a.has(d))),u=CS({contract:i.children.contract,integrated:[...a],active:[...l],maxParallel:n.coordination_mode==="single-session"?1:r.outcome.output.maxParallelChildren??2}),f=r.outcome.output;return a.size===i.children.contract.children.length?{state:n,next:[{stepId:"supervisor.parent.builder",input:{contractRef:n.children_contract_ref,integrationBranch:o.integrationBranch,integrationWorktree:o.integrationWorktree,integrationCommit:f.integrationCommit,acceptance:n.acceptance.map(({id:d,source:p,text:m})=>({id:d,source:p,text:m}))}}]}:{state:n,next:u.map(d=>({stepId:"supervisor.child.prepare",input:{child:d,contractRef:n.children_contract_ref,integrationBranch:o.integrationBranch,integrationWorktree:o.integrationWorktree,targetCommit:f.integrationCommit}}))}}if(r.kind==="action-outcome"&&r.stepId==="build.builder"){if(r.outcome.status==="failed")return{state:n,next:[{stepId:"build.resume",input:{failedBuilderActionId:r.outcome.actionId}}]};let i=t.actions.find(a=>a.id===r.outcome.actionId);if(!i)throw new Error("Native Builder Action is missing from its Run");let o=_W(t,i,r.outcome);return{state:Ui(o),next:["verify.verifier"]}}if(r.kind==="wait-resolved"&&r.stepId==="build.resume"){let a=t.waits.find(s=>s.stepId==="build.resume"&&s.decision?.id===r.decisionId&&s.proposalHash===r.proposalHash)?.proposal?.activation?.failedBuilderActionId;if(typeof a!="string"||!t.actions.some(s=>s.id===a&&s.stepId==="build.builder"&&s.status==="failed"))throw new Error("Native SDK Builder continuation lacks its failed Action");return{state:n,next:[{stepId:"build.builder",input:{failedBuilderActionId:a}}]}}if(r.kind==="action-outcome"&&r.stepId==="supervisor.parent.builder"){if(r.outcome.status==="failed"){let a=t.actions.find(c=>c.id===r.outcome.actionId),s=a?.input?.activation;if(!s||!a)throw new Error("Native SDK Supervisor parent Builder failure lacks its Action");return{state:n,next:[{stepId:"supervisor.parent.resume",input:{...s,failedBuilderActionId:a.id}}]}}let i=t.actions.find(a=>a.id===r.outcome.actionId);if(!i)throw new Error("Native Supervisor parent Builder Action is missing");let o=_W(t,i,r.outcome);return{state:Ui(o),next:["verify.verifier"]}}if(r.kind==="wait-resolved"&&r.stepId==="supervisor.parent.resume"){let o=t.waits.find(a=>a.stepId==="supervisor.parent.resume"&&a.decision?.id===r.decisionId&&a.proposalHash===r.proposalHash)?.proposal?.activation;if(!o||typeof o.failedBuilderActionId!="string"||!t.actions.some(a=>a.id===o.failedBuilderActionId&&a.stepId==="supervisor.parent.builder"&&a.status==="failed"))throw new Error("Native SDK Supervisor parent continuation lacks its failed Action");return{state:n,next:[{stepId:"supervisor.parent.builder",input:o}]}}if(r.kind==="action-outcome"&&r.stepId==="verify.verifier"){let i=t.actions.find(a=>a.id===r.outcome.actionId);if(!i)throw new Error("Native Verifier Action is missing from its Run");if(r.outcome.status==="failed"){let a=R5(t,i,r.outcome);return a.status==="blocked"?{state:a,next:["verify.retry"]}:{state:Ui(a),next:["verify.verifier"]}}let o=A5(t,i,r.outcome);return{state:o.state,next:o.state.verification_result==="pass"?[{stepId:"verify.confirm",input:{report:iv(o.state,t.input.artifactRootRef)}}]:o.state.phase==="build"?n.children_contract_ref?[{stepId:"supervisor.parent.builder",input:Fv(t,{failedVerifierActionId:i.id})}]:[{stepId:"build.builder",input:{repairContext:Dd(o.state,t)}}]:["verify.stop"]}}if(r.kind==="wait-resolved"&&r.stepId==="verify.stop"){let i=t.waits.find(c=>c.stepId===r.stepId&&c.decision?.id===r.decisionId&&c.proposalHash===r.proposalHash);if(!i||!Ls(n,i,t).some(({choice:c})=>c===r.choice))throw new Error("Native Verify stop decision does not match the current Run");if(r.choice==="retry")return{state:Ui(XN(n,{reason:i.decision?.reason})),next:[{stepId:"verify.verifier",input:{recoveryWaitId:i.id,...i.decision?.reason===void 0?{}:{reason:i.decision.reason}}}]};let o=xl({state:n,reason:"The user chose to revise the implementation after Verify stopped."}),a=[...t.actions].reverse().find(c=>c.stepId==="verify.verifier"&&c.status==="succeeded"),s=a?void 0:t.actions.find(c=>c.stepId==="verify.checks"&&c.status==="failed"&&t.actionContexts[c.id].sequence===i.results["verify.checks"]?.sequence);if(!a&&!s)throw new Error("Native Verify stop has no original failed result");return{state:o,next:n.children_contract_ref?[{stepId:"supervisor.parent.builder",input:Fv(t,a?{failedVerifierActionId:a.id}:{failedCheckActionId:s.id})}]:[{stepId:"build.builder",input:{repairContext:Dd(o,t)}}]}}if(r.kind==="wait-resolved"&&r.stepId==="verify.retry")return{state:Ui(eS(n)),next:["verify.verifier"]};if(r.kind==="wait-resolved"&&r.stepId==="verify.confirm"){let i=t.waits.find(a=>a.stepId===r.stepId&&a.decision?.id===r.decisionId&&a.proposalHash===r.proposalHash);if(!i||!Ls(n,i,t).some(({choice:a})=>a===r.choice))throw new Error("Native Verify confirmation does not match an executable current decision");if(r.choice==="reverify"){let a=M({...n,status:"active",state_version:n.state_version+1,verification:null,verification_result:"pending",verification_report:null,acceptance:n.acceptance.map(s=>({...s,result:"pending",reason:null})),loop:{...n.loop,stage:"verify-ready",next_action:"run-required-checks-and-dispatch-verifier"}});return{state:Ui(a),next:["verify.verifier"]}}if(r.choice==="approved")return N5(t,n);let o=xl({state:n,reason:"The user rejected the Skill-coordinated Verifier pass."});return{state:o,next:n.children_contract_ref?[{stepId:"supervisor.parent.builder",input:Fv(t,{rejectedDecisionId:r.decisionId})}]:[{stepId:"build.builder",input:{repairContext:Dd(o,t)}}]}}if(r.kind==="action-outcome"&&["archive.prepare","archive.execute"].includes(r.stepId)&&r.outcome.status==="failed"&&r.outcome.output.reason==="candidate-drift")return{state:M({...n,phase:"verify",status:"await-user",state_version:n.state_version+1,verification:null,verification_result:"pending",verification_report:null,acceptance:n.acceptance.map(o=>({...o,result:"pending",reason:null})),blockers:[{owner:"user",reason:Ct("归档候选已变化;由 Agent 核对实际修改,选择修订实现或重新验收。"),acceptance_ids:[],resolution_action:"await-user"}],loop:{...n.loop,stage:"await-user",next_action:"await-user"}}),next:["verify.stop"]};if(r.kind==="action-outcome"&&r.stepId==="supervisor.parent.deliver")return{state:n,next:r.outcome.status==="succeeded"?["archive.prepare"]:[]};if(r.kind==="action-outcome"&&r.stepId==="archive.prepare")return{state:n,next:r.outcome.status==="succeeded"?["archive.execute"]:[]};if(r.kind==="action-outcome"&&r.stepId==="archive.execute")return r.outcome.status!=="succeeded"?{state:n,next:[]}:{state:M({...n,status:"done",archived:!0,state_version:n.state_version+1,blockers:[],loop:{...n.loop,stage:"done",next_action:null}}),next:["archive.finalize"]};if(r.kind==="action-outcome"&&r.stepId==="archive.finalize")return{state:n,next:r.outcome.status==="succeeded"&&n.children_contract_ref?["supervisor.cleanup"]:[]};if(r.kind==="action-outcome"&&r.stepId==="supervisor.cleanup")return{state:n,next:[]};throw new Error(`Native SDK does not handle ${r.stepId} yet`)}},validators:[Cv,xv,Sv,Av,HS,QS,JS,mv,hv,gv,Pv,Tv,Dv,Bv,Vv,Lv,US,qv,Wv,$v],stateValidators:[zS],commandValidators:[Ev,Iv,Nv,bv],executors:[RS,aW,nW,tW,vS,wS,Vf,IS,xS,qS,WS,jv,$S]}}var HS,QS,US,JS,zS,Ff=x(()=>{"use strict";lt();Cr();He();Ft();QN();it();Sr();ze();lr();eo();Cr();bo();Et();Vs();St();Sa();Se();io();Jc();vs();vv();yv();rW();iW();Co();Mf();ES();dW();pW();DS();kW();NW();BS();Hs();Qs();VS();rS();ai();rn();Bd();HS={id:"comet-native-shape-outcome",version:"1",async validate({run:e,action:t,outcome:r,context:n}){if(r.status==="failed")return{accepted:!0};let i=e.input;if(!n?.projectRoot||typeof i.name!="string"||typeof i.artifactRootRef!="string"||!["shape.prepare","shape.revalidate"].includes(t.stepId))return{accepted:!1,reason:"Native Shape lacks its project and Action"};try{let o=Js(r.output);if(M(e.state).name!==i.name||!Array.isArray(o.acceptance)||o.acceptance.length===0||!Array.isArray(o.specChanges))throw new Error("Native Shape requires its change, specifications and acceptance criteria");return{accepted:!0}}catch(o){return{accepted:!1,reason:String(o)}}}},QS={id:"comet-native-builder-outcome",version:"1",async validate({run:e,outcome:t,context:r}){if(t.status==="failed")return{accepted:!0};let n=e.input;if(!r?.projectRoot||typeof n.name!="string"||typeof n.artifactRootRef!="string")return{accepted:!1,reason:"Native Builder result lacks its project binding"};try{if(M(e.state).name!==n.name)return{accepted:!1,reason:"Native Builder result belongs to another change"};let o=await Te(r.projectRoot);if(!o||o.native.artifact_root!==n.artifactRootRef)return{accepted:!1,reason:"Native artifact root changed after Run creation"};let a=t.output;if(["3","4"].includes(e.workflow.version)&&a?.requireIndependentReview!==void 0&&typeof a.requireIndependentReview!="boolean")throw new Error("requireIndependentReview must be a boolean");{if(a?.response||a?.verificationChecks!==void 0)throw new Error("Run checks with platform tools and submit checks reports, not Runtime check plans.");return{accepted:!0}}}catch(i){return{accepted:!1,reason:i instanceof Error?i.message:String(i)}}}},US={id:"native-supervisor-parent-builder-outcome",version:"1",async validate({run:e,action:t,outcome:r,context:n}){if(r.status==="failed")return{accepted:!0};if(!n?.projectRoot||t.stepId!=="supervisor.parent.builder"||t.type!=="handoff")return{accepted:!1,reason:"Native Supervisor parent Builder lacks its project"};try{let i=await $l(e,n.projectRoot),o=t.input.activation,a=i.state,s=It(n.projectRoot,a.name),c=Nt(a.name),l=Bl(t,r),u=new Set(ur(e).filter(f=>f.stepId==="supervisor.child.archive"&&f.status==="succeeded").map(f=>f.input.activation.child));if(a.phase!=="build"||!o||Ke(o,e)!==a.children_contract_ref||o.integrationBranch!==c||typeof o.integrationWorktree!="string"||!ye(o.integrationWorktree,s)||typeof o.integrationCommit!="string"||ue(s).currentBranch!==c||pe(s,c)!==l||u.size!==i.contract.children.length||i.contract.children.some(({name:f})=>!u.has(f)))throw new Error("Native Supervisor parent candidate is not the complete integration");return te(s,["merge-base","--is-ancestor",o.integrationCommit,l]),{accepted:!0}}catch(i){return{accepted:!1,reason:i instanceof Error?i.message:String(i)}}}},JS={id:"comet-native-verifier-outcome",version:"1",async validate({run:e,outcome:t,context:r}){let n=e.input;if(!r?.projectRoot||typeof n.artifactRootRef!="string")return{accepted:!1,reason:"Native Verifier result lacks its project binding"};try{if(t.status==="failed")return{accepted:!0};let i=await Te(r.projectRoot);if(!i||i.native.artifact_root!==n.artifactRootRef||(n.maxVerifyFailures??xu)!==i.native.max_verify_failures)return{accepted:!1,reason:"Native project configuration changed after Run creation"};if(t.output?.response?.kind==="request-checks")throw new Error("Run additional checks with platform tools and report the final result.");return{accepted:!0}}catch(i){return{accepted:!1,reason:i instanceof Error?i.message:String(i)}}}},zS={id:"comet-native-state",version:"1",validate({state:e}){try{return M(e),{accepted:!0}}catch(t){return{accepted:!1,reason:t instanceof Error?t.message:String(t)}}}}});var OW={};fw(OW,{upgradeNativeRun:()=>Ea});function Ea(e,t,r){let n=Bn(t),i=D(n);if(e.workflow.hash===i&&e.workflow.version===n.version)return e;if(e.workflow.version==="4"&&e.workflow.hash!==E5)throw new Error("Native 当前 Run 的 definition hash 不匹配;不能作为旧业务数据重新绑定。");if(e.workflow.id!=="comet-native"||!["1","2","3","4"].includes(e.workflow.version))throw new Error("Native Run 不属于可升级的内置协议");let o=M(e.state);if(o.name!==e.runId||e.input?.name!==e.runId)throw new Error("Native Run 与需求名称不一致");let a=KA(e);a.state=o;let s=d=>Object.hasOwn(n.steps,d),c=[],l={"verify.checks-stop":"verify.stop","supervisor.child.checks-stop":"supervisor.child.verifier-retry","supervisor.child.integration-checks-stop":"supervisor.child.verifier-retry"};for(let d of a.actions)s(d.stepId)||!["pending","running","unknown"].includes(d.status)||(c.push({step:d.stepId,results:a.actionContexts[d.id].results}),d.status="cancelled",d.reason="旧检查调度已移交 Agent 平台;原进程结果未确认,不代表已经停止或通过。");for(let d of a.waits)if(!(d.status!=="pending"||s(d.stepId))){if(l[d.stepId]){d.stepId=l[d.stepId];continue}throw new Error("旧 Native 待决定事项没有当前业务对应项,原提案保持不变。")}for(let d of a.evidenceWaits??[])d.status==="pending"&&!s(d.stepId)&&(c.push({step:d.stepId,results:d.results}),d.status="cancelled");let u=a.ready;a.ready=u.filter(d=>s(d.to)&&(d.from===null||s(d.from)));for(let d of u)(!s(d.to)||d.from!==null&&!s(d.from))&&c.push({step:d.to,results:d.results});if(e.status==="failed"&&e.reason?.startsWith("ACTION_FAILED: ")){let d=e.reason.slice(15),p=[...a.actions].reverse().find(m=>m.stepId===d);!s(d)&&p&&c.push({step:d,results:a.actionContexts[p.id].results})}if(o.children_contract_ref&&!a.actions.some(d=>d.id===o.children_contract_ref)){let d=[...a.waits].reverse().find(h=>["shape.confirm","supervisor.shape.confirm"].includes(h.stepId)&&h.status==="resolved"&&["approved","single-session","multi-session"].includes(h.decision?.choice??"")),p=a.actions.find(h=>h.stepId==="shape.prepare"&&h.status==="succeeded"&&a.actionContexts[h.id].sequence===d?.results["shape.prepare"]?.sequence),m=p?.outcome?.output?.children?.contract;if(!p||!m)throw new Error("旧 Supervisor 缺少原已批准的子任务方案");a.state={...o,children_contract_hash:o.children_contract_ref,children_contract_ref:p.id,children_contract:m}}let f=new Set;for(let d of c){if(["completed","cancelled"].includes(e.status))break;if(a.waits.some(v=>v.status==="pending"&&["verify.stop","verify.confirm","verify.retry"].includes(v.stepId))&&!d.step.startsWith("supervisor.child."))continue;let m=["shape.revalidate","build.checks"].includes(d.step)?["shape.confirm","supervisor.shape.confirm"]:d.step==="verify.revalidate"?["verify.confirm"]:[],h=[...a.waits].reverse().find(v=>m.includes(v.stepId)&&v.status==="resolved"&&d.results[v.stepId]?.sequence===v.sequence&&["approved","single-session","multi-session"].includes(v.decision?.choice??"")),g;if(h){let v;if(d.step==="build.checks")v={state:a.state,next:["build.builder"]};else{if(!r)throw new Error("旧批准需要当前业务转移器完成数据转换");v=r.apply({run:a,event:{kind:"wait-resolved",stepId:h.stepId,choice:h.decision.choice,proposalHash:h.proposalHash,decisionId:h.decision.id}})}if(v.next.length!==1)throw new Error("旧批准没有唯一的当前业务续行");a.state=v.state;let w=v.next[0];g={from:h.stepId,to:typeof w=="string"?w:w.stepId,results:{...h.results,[h.stepId]:{sequence:h.sequence,value:{choice:h.decision.choice,proposal:h.proposal}}},...typeof w=="string"?{}:{activation:w.input}}}else{let v=[...a.actions].reverse().find(N=>s(N.stepId)&&N.status==="succeeded"&&["build.builder","supervisor.parent.builder","supervisor.child.builder","supervisor.child.integrate","supervisor.child.integration-repair","verify.verifier"].includes(N.stepId)&&d.results[N.stepId]?.sequence===a.actionContexts[N.id].sequence);if(!v)throw new Error("旧 Native Run 缺少已接受的业务续行来源,原记录保持不变。");if(f.has(v.id))continue;f.add(v.id);let w=a.actionContexts[v.id],y,R;if(["supervisor.child.builder","supervisor.child.integrate","supervisor.child.integration-repair"].includes(v.stepId)){if(!r)throw new Error("旧 Child 需要当前业务转移器完成数据转换");let N=r.apply({run:a,event:{kind:"action-outcome",stepId:v.stepId,outcome:v.outcome}});if(N.next.length!==1)throw new Error("旧 Child 没有唯一的当前业务续行");a.state=N.state;let b=N.next[0];y=typeof b=="string"?b:b.stepId,R=typeof b=="string"?void 0:b.input,R&&typeof R=="object"&&!Array.isArray(R)&&(R={...R,contractRef:M(a.state).children_contract_ref},delete R.contractHash)}else{let N=M(a.state),b=v.stepId==="verify.verifier"&&N.verification_result==="pass";y=b?"verify.confirm":"verify.verifier",!b&&N.phase==="verify"&&N.loop.stage==="verify-ready"&&N.loop.next_action!=="await-verifier-result"&&(a.state=Ui(N))}g={from:v.stepId,to:y,results:{...w.results,[v.stepId]:{sequence:w.sequence,value:v.outcome.output}},...R===void 0?{}:{activation:R}}}g.to==="verify.confirm"&&(g.activation={report:iv(M(a.state),a.input.artifactRootRef)}),a.ready.push(g),a.status="running",delete a.reason}a.workflow={id:n.id,version:n.version,hash:i};for(let d of Object.keys(a.definitionHashes))JSON.parse(d)[0]===n.id&&delete a.definitionHashes[d];return a.definitionHashes[JSON.stringify([n.id,n.version])]=i,a}var E5,Hv=x(()=>{"use strict";Vs();Co();ze();Se();E5="26c4e50c65dcb5e1280529642a73b650400e3109ba6fa2efded90e03ad790443"});bo();Oi();ai();Ft();nN();lr();tl();Xo();iN();it();import Of from"path";import{realpathSync as k8}from"fs";function R$(e){return e.map(t=>/^[A-Za-z0-9_./:=+@-]+$/u.test(t)?t:`'${t.replace(/'/gu,`'"'"'`)}'`).join(" ")}function N$(e,t){let r=h=>h!==null&&typeof h=="object"&&!Array.isArray(h)?h:{},n=r(e),i=r(n.entry),o=r(n.run??i.run??(typeof n.runId=="string"?n:void 0)),a=r(n.state??i.state??n),s=r(n.preparation??n.workspace??i.workspace),c=r(n.continuation??i.continuation??n.nextAction??i.nextAction),l=typeof s.projectRoot=="string"&&s.projectRoot!=="."?s.projectRoot:typeof c.cwd=="string"?c.cwd:typeof n.projectRoot=="string"?n.projectRoot:typeof i.projectRoot=="string"?i.projectRoot:t??null,u=a.stateVersion??a.state_version,f=a.status??o.status,{current:d,...p}=c,m=d===void 0?c:{...p,currentRef:n.continuation!==void 0?"data.continuation.current":"data.entry.continuation.current"};return{phase:typeof a.phase=="string"?a.phase:null,status:typeof f=="string"?f:null,stateVersion:typeof u=="number"?u:null,workspace:{cwd:l},continuation:Object.keys(c).length?{...m,cwd:l}: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}}:{}}}var Mi={next:"NEXT:",relay:"RELAY TO USER:",detail:"DETAIL:",details:"--- machine projection (run with --json to consume it) ---"};function S$(e){return e?e.command?`${Mi.next} ${e.command}`:e.ask_user?`${Mi.next} ${e.ask_user}`:e.instruction?`${Mi.next} ${e.instruction}`:null:null}function E$(e,t){let r=[e.summary],n=S$(e.next);return n&&r.push(n),e.user_message&&r.push("",Mi.relay,e.user_message),t!==void 0&&r.push("",Mi.details,JSON.stringify(t,null,2)),`${r.join(`
|
|
426
|
+
`)}
|
|
427
|
+
`}function C$(e,t,r){let n=[e.summary],i=S$(e.next);return i&&n.push(i),e.user_message&&n.push("",Mi.relay,e.user_message),n.push("",`${Mi.detail} ${t}`),r!==void 0&&n.push("",Mi.details,JSON.stringify(r,null,2)),n.join(`
|
|
428
|
+
`)}He();Et();function Ee(e,t,r){return e==="zh-CN"?r:t}var oN={shape:{en:"Shape (agreeing on requirements)",zh:"Shape(需求共识)"},build:{en:"Build",zh:"Build(实现)"},verify:{en:"Verify",zh:"Verify(验证)"},archive:{en:"Archive",zh:"Archive(归档)"}};function _$(e,t){return typeof e=="string"&&oN[e]?Ee(t,oN[e].en,oN[e].zh):typeof e=="string"?e:""}function aN(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;let t=e;return typeof t.total=="number"&&typeof t.passed=="number"&&typeof t.failed=="number"&&typeof t.blocked=="number"&&typeof t.pending=="number"}function B4(e){let t={total:e.length,passed:0,failed:0,blocked:0,pending:0};for(let r of e){if(!r||typeof r!="object")return null;let n=r.result;if(n!=="passed"&&n!=="failed"&&n!=="blocked"&&n!=="pending")return null;t[n]+=1}return t}function I$(e,t){let r=[];e.failed>0&&r.push(Ee(t,`${e.failed} failed`,`${e.failed} 项失败`)),e.blocked>0&&r.push(Ee(t,`${e.blocked} blocked`,`${e.blocked} 项受阻`)),e.pending>0&&r.push(Ee(t,`${e.pending} pending`,`${e.pending} 项待验`));let n=Ee(t,`acceptance ${e.passed}/${e.total} passed`,`验收 ${e.passed}/${e.total} 通过`);return r.length>0?`${n} (${r.join(", ")})`:n}function x$(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;let t=e;if(typeof t.change!="string"||t.disposition!=="continue"&&t.disposition!=="await-user"&&t.disposition!=="blocked"&&t.disposition!=="done"||t.commandArgs!==null&&t.commandArgs!==void 0&&!Array.isArray(t.commandArgs))return!1;let r=t.userCommunication;return!!(r&&typeof r=="object"&&typeof r.required=="boolean"&&(r.message===null||typeof r.message=="string")&&typeof r.agentInstruction=="string")}function sN(e){return/[\u4e00-\u9fff]/u.test(e.userCommunication.agentInstruction)?"zh-CN":"en"}function W4(e,t,r){return e==="done"?Ee(r,"complete","已完成"):e==="await-user"?Ee(r,"waiting for a user decision","等待用户决定"):e==="blocked"?Ee(r,"paused: needs attention","已暂停,需要处理"):t?Ee(r,"waiting for a user decision","等待用户决定"):Ee(r,"ready to continue","可继续推进")}function q4(e,t,r){let n=sN(e),i=[];r&&i.push(r);let o=Ee(n,`Change ${e.change}`,`需求 ${e.change}`),a=_$(e.phase,n),s=e.mode==="wait"?Ee(n,"waiting for the original task","等待原任务完成"):W4(e.disposition,e.userCommunication.required,n);i.push([o,a||null,s].filter(Boolean).join(" · ")),t&&t.total>0&&i.push(I$(t,n));let c=e.userCommunication,l=P$(e,n);return{summary:i.join("; "),...l?{next:l}:{},...c.required&&c.message?{user_message:c.message}:{}}}function P$(e,t){let r=e.userCommunication;return e.mode&&e.mode!=="execute"?e.mode==="ask"?{ask_user:r.agentInstruction}:{instruction:r.agentInstruction}:e.disposition==="await-user"&&r.required?{ask_user:Ee(t,"Relay the message below, wait for the user decision, then run the matching option (run with --json to see the exact alternative commands).","先转述下方信息并等待用户选择,再执行对应命令(完整候选命令以 --json 输出为准)。")}:e.commandArgs&&e.commandArgs.length>0?{command:R$(e.commandArgs)}:e.disposition==="done"?{ask_user:Ee(t,"No further workflow action; report the completed change to the user.","工作流已无后续动作;向用户报告该需求已完成即可。")}:e.disposition==="blocked"?{ask_user:r.required&&r.message?r.agentInstruction:Ee(t,"Resolve the paused condition before continuing; run with --json for the structured diagnosis.","先解除暂停原因再继续;结构化诊断信息以 --json 输出为准。")}:{instruction:r.agentInstruction}}function L4(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;let t=e;return typeof t.total=="number"&&Array.isArray(t.items)}function V4(e,t){let r=typeof e.name=="string"?e.name:"(unnamed)",n=_$(e.phase,t),i=e.status==="await-user"?Ee(t,"waiting for a user decision","等待用户决定"):e.status==="blocked"?Ee(t,"paused","已暂停"):e.status==="done"?Ee(t,"complete","已完成"):Ee(t,"in progress","进行中"),o=aN(e.acceptance)?`${Ee(t,", ",",")}${I$(e.acceptance,t)}`:"";return` ${r} · ${n||String(e.phase??"?")} · ${i}${o}`}function M4(e){for(let t of e){let r=t.continuation;if(r?.userCommunication&&typeof r.userCommunication.agentInstruction=="string"&&/[\u4e00-\u9fff]/u.test(r.userCommunication.agentInstruction))return"zh-CN"}return"en"}function F4(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;let t=e;return typeof t.healthy!="boolean"?!1:t.findings===void 0||Array.isArray(t.findings)}function H4(e){if(e.healthy){let n=e.repaired?Ee("en","Diagnostics passed and the reported problem was repaired automatically.","诊断通过,报告的问题已自动修复。"):Ee("en","Diagnostics passed: no problems found.","诊断通过:未发现问题。"),i=Q4(e.continuation);return i?{summary:n,next:i}:{summary:n}}let r=Array.isArray(e.findings)?e.findings.length:0;return{summary:Ee("en",r>0?`Diagnostics found ${r} problem${r===1?"":"s"} that need attention before this change can continue.`:"Diagnostics found problems that need attention before this change can continue.",r>0?`诊断发现 ${r} 个需要处理的问题,处理后该需求才能继续。`:"诊断发现需要处理的问题,处理后该需求才能继续。"),next:{ask_user:Ee("en","Run with --json to read the structured findings; re-run with --repair once the cause is understood.","结构化诊断以 --json 输出为准;确认原因后再用 --repair 修复。")}}}function Q4(e){return x$(e)?P$(e,sN(e)):void 0}function T$(e){if(!e||typeof e!="object"||Array.isArray(e))return;let t=e;if(F4(t))return H4(t);if(L4(t)){let n=M4(t.items);return{summary:[t.total===t.items.length?Ee(n,`Native changes (${t.total})`,`Native 需求列表(共 ${t.total} 条)`):Ee(n,`Native changes (showing ${t.items.length} of ${t.total})`,`Native 需求列表(显示 ${t.items.length}/${t.total} 条)`),...t.items.map(o=>V4(o,n))].join(`
|
|
429
|
+
`)}}let r=t.continuation;if(x$(r)){let n=sN(r),i=q4(r,U4(t),z4(t,n));return J4(t)==="unconfirmed"?{...i,summary:`${i.summary}${Ee(n,"; the dispatched Verifier has not confirmed startup yet — verify the subagent actually launched before waiting on it",";已派发的 Verifier 尚未确认启动——先核实子代理确实启动,再继续等待")}`}:i}if(typeof t.artifactRoot=="string"&&typeof t.nativeRoot=="string"){let n=t.language==="zh-CN"?"zh-CN":"en",i="pendingRootMove"in t;return{summary:Ee(n,i?`Comet Native artifacts live under ${t.artifactRoot} (state root: ${t.nativeRoot}).`:`Initialized Comet Native at ${t.nativeRoot} (artifacts: ${t.artifactRoot}).`,i?`Comet Native 产物位于 ${t.artifactRoot}(状态根目录:${t.nativeRoot})。`:`Comet Native 已初始化于 ${t.nativeRoot}(产物目录:${t.artifactRoot})。`)}}}function U4(e){if(aN(e.acceptance))return e.acceptance;let t=e.state;if(t&&typeof t=="object"&&!Array.isArray(t)){let r=t;if(aN(r.acceptance))return r.acceptance;if(Array.isArray(r.acceptance))return B4(r.acceptance)}return null}function J4(e){let t=e.localExecution;if(!t||typeof t!="object"||Array.isArray(t))return;let r=t.verifierStartup;if(!(!r||typeof r!="object"||Array.isArray(r)))return r.confirmation}function z4(e,t){if(e.selected!==void 0&&typeof e.selected=="string")return Ee(t,`Selected ${e.selected}.`,`已选择需求 ${e.selected}。`);let r=e.migration;return r&&typeof r=="object"&&r.completed===!0?Ee(t,"Upgraded this change to the current Native format.","已将该需求升级到当前 Native 格式。"):null}function O$(e){let r=e.data&&typeof e.data=="object"&&!Array.isArray(e.data)?e.data:{};switch(e.code){case"document-invalid":return{summary:e.message,...typeof r.change=="string"?{next:{command:`comet native next ${r.change} --summary <summary>`}}:{}};case"conflict":return{summary:r.outcome==="revision-conflict"||/^expected revision \d+, got \d+$/iu.test(e.message)?Ee("en","This change was updated by another operation. Read the latest state and continue from its current instructions.","这条需求已被另一个操作更新。请读取最新状态,按当前指引继续。"):e.message,...typeof r.change=="string"?{next:{command:`comet native status ${r.change} --json`}}:{}};case"baseline-incomplete":return{summary:Ee("en","The safety snapshot for this change exceeded its configured size budget, so the command stopped before changing anything. Raise the snapshot limits in .comet/config.yaml or exclude out-of-scope data, then retry.","该需求的安全快照超出配置的容量预算,命令在改动任何内容前已停止。请在 .comet/config.yaml 中调高快照上限,或将范围外的数据加入排除列表后重试。"),next:{ask_user:Ee("en","Run with --json to see the exact limits, omitted paths, and supported fixes.","具体上限、被省略的路径和支持的修复方式以 --json 输出为准。")}};case"workspace-isolation-required":return{summary:Ee("en","This change runs in its own Git worktree to keep work isolated. Create the linked worktree first, then continue inside it.","这条需求需要在独立的 Git worktree 中执行以保证隔离。请先创建关联的 worktree,然后在其中继续。"),next:{ask_user:Ee("en","Run with --json to see the exact worktree creation command.","完整的 worktree 创建命令以 --json 输出为准。")}};case"workspace-preparation-incomplete":return{summary:Ee("en","The change workspace is not fully prepared (for example a branch or worktree is missing). Finish the preparation steps, then retry.","需求的工作区尚未准备完成(例如分支或 worktree 缺失)。请先完成准备步骤,再重试。"),next:{ask_user:Ee("en","Run with --json to see the remaining preparation steps.","剩余的准备步骤以 --json 输出为准。")}};case"implementation-scope-stale":return{summary:Ee("en","The recorded implementation scope no longer matches the current files. Refresh the scope, then retry.","记录的实现范围与当前文件不再一致。请刷新范围后重试。"),next:{ask_user:Ee("en","Run with --json to see the exact recovery steps.","具体恢复步骤以 --json 输出为准。")}};default:return}}var Pg=class extends Error{recovery;constructor(t,r){super(t),this.name="NativeReceiptScopeStaleError",this.recovery=r}};Am();tv();Sm();var wB=["--project-root <path> Resolve the Native project from this working directory.","--json Emit the stable JSON command envelope.","--compact 与 --json 合用;重复字段用 outputView.references 的 JSON Pointer 定位,Request 模板保留完整;没有字节收益时返回原完整协议。去掉此选项获取完整协议。","--verbose Append the raw machine projection after the human/agent text.","--help Show help without requiring an initialized project."],MN=Object.freeze({"":{usage:"comet native <command> [options]",purpose:"Create, inspect, recover, and archive portable Native changes through Runtime-enforced, skill-coordinated steps.",agentQuickStart:["Run `comet native status --json` to discover active changes.","Select an existing change with `select`, or create one with `new`.","After Shape approval, new ordinary SDK tasks use `next <change> --session <actual-session>`. Submit business results using the returned command. Runtime checks and the next task are returned together. Older and Supervisor tasks retain their returned protocol through `comet runtime dispatch --application native`; read continuation.inputOptions when present.","For compat Runtime changes, execute `agent.continuation.commandArgs` in `agent.workspace.cwd` and fill `agent.continuation.inputOptions` templates."],subcommands:["init Initialize Native project configuration.","root show Inspect the configured artifact root.","root move <artifact-root> Move the configured artifact root.","new <change-name> Create a change and prepare its workspace.","spec disassociate Revoke a capability association through Runtime.","spec remove Record a complete capability removal intent.","spec sync <change-name> <capability> --input <json-file> Audit local Markdown reference corrections.","show <change-name> Read formal artifacts and portable state.","status [<change-name>] Discover stable boundaries and Runner actions.","select <change-name> Select a change in its bound workspace.","next <change-name> Confirm or recover a stable workflow boundary.","archive <change-name> Preview and execute Archive plus workspace finish.","cancel <change-name> Cancel an unfinished change while keeping its code and workspace.","doctor [<change-name>] Diagnose, migrate, or rebuild local execution state.","transfer export|import Move an active Supervisor Child Build to another checkout."],options:wB,output:"A human summary plus a NEXT step by default (RELAY TO USER blocks carry user decisions); use --json for the structured envelope, --verbose to append the raw machine projection.",examples:["comet native status --json","comet native status my-change --details --json","comet native next --help"]},init:{usage:"comet native init [--root <artifact-root>] [--language en|zh-CN]",purpose:"Create or normalize .comet/config.yaml and the configured Native directories.",options:["--root <artifact-root> Project-relative artifact root; defaults to docs.","--language en|zh-CN Language for newly generated Native artifacts."],output:"The resolved project configuration and Native paths.",examples:["comet native init --root docs --language zh-CN"]},root:{usage:"comet native root <show|move> [arguments]",purpose:"Inspect or transactionally move the configured Native artifact root.",subcommands:["show Print the configured artifact root and resolved paths.","move <artifact-root> Move Native artifacts and update project configuration."],output:"The current root projection or the completed move result.",examples:["comet native root show","comet native root move artifacts/native"]},"root show":{usage:"comet native root show",purpose:"Print the configured Native artifact root and resolved paths.",output:"The configured artifact root and resolved Native paths."},"root move":{usage:"comet native root move <artifact-root>",purpose:"Transactionally move Native artifacts and update project configuration.",output:"The source, destination, and committed root-move transaction result.",examples:["comet native root move artifacts/native"]},new:{usage:"comet native new <change-name> [--runtime compat|sdk] [--language en|zh-CN] [--task <text>] [--capability <id>] [--isolation current|branch|worktree] [--change-branch <branch>] [--target-branch <branch>] [--worktree-path <path>]",purpose:"Create a portable Native change and prepare the requested branch or linked worktree.",options:["--runtime compat|sdk Runtime format for this new change; defaults to sdk.","--language en|zh-CN Artifact language; defaults to project configuration.","--task <text> Preserve the original request in the SDK Run for independent alignment review; also search Project Knowledge for a capability association.","--capability <id> Directly validate and associate an existing capability without retrieval.","--isolation <kind> current, branch, or worktree; defaults to current.","--change-branch <branch> Change branch; defaults to comet/<change-name>.","--target-branch <branch> Local base branch; defaults to the current branch.","--worktree-path <path> Worktree directory; defaults to .worktrees/<change-name>."],output:"The SDK Run or portable state, canonical artifact paths, and workspace preparation result; compat Runtime changes include the next Runner continuation.",examples:["comet native new session-timeout --language zh-CN",'comet native new add-sms-login --task "add SMS login to authentication"',"comet native new session-timeout --isolation branch --target-branch main","comet native new session-timeout --isolation worktree --target-branch main"]},spec:{usage:`comet native spec disassociate <change-name> --expected-state-version <n> --expected-action disassociate-capability
|
|
430
|
+
comet native spec remove <change-name> <capability>
|
|
431
|
+
comet native spec sync <change-name> <capability> --input <json-file>`,purpose:"Record a capability removal; create and modify intents use complete proposed Spec files.",subcommands:["disassociate <change-name> Revoke a capability association and return to Shape.","remove <change-name> <capability> Record a capability removal.","sync <change-name> <capability> --input <json-file> Compat-only Markdown reference correction; SDK changes return to Shape for revision."],output:"The updated portable state and continuation."},"spec remove":{usage:"comet native spec remove <change-name> <capability>",purpose:"Record removal of a capability in the complete target specification.",output:"The updated portable state and continuation with the next Runner action."},"spec disassociate":{usage:"comet native spec disassociate <change-name> --expected-state-version <n> --expected-action disassociate-capability",purpose:"Revoke a capability association through Runtime without hand-editing artifacts.",options:["--expected-state-version <n> State version returned by the latest status response.","--expected-action <action> Must be disassociate-capability."],output:"The updated portable state and continuation with the next Runner action."},"spec snapshot":{usage:"comet native spec snapshot <change-name>",purpose:"Restore the originally approved documents first. Runtime checks their complete legacy fingerprint and saves at most 2 MiB of original evidence in this workspace Runtime. It does not approve changed requirements or change the Run, candidate, Action, claim or check receipts. Evidence is local to this workspace; repeat the verified capture after moving to another device.",output:"The validated original Shape identity and captured sources; no workflow state changes."},"spec sync":{usage:"comet native spec sync <change-name> <capability> --input <json-file>",purpose:"Compat-only reference correction. SDK changes use Shape edits or next --revise-requirements from Verify/Archive.",options:["--input <json-file> Fields: expectedStateVersion, actor, reason, affectedAcceptanceIds, replacements [{from,to}]. Include all acceptance IDs from the affected spec."],output:"For compat Runtime changes, the audited state and Build continuation for re-verification. SDK changes receive revise-requirements guidance."},show:{usage:"comet native show <change-name>",purpose:"Read formal artifacts and portable state for one Native change.",output:"A compact summary and NEXT action by default. Use --json to read canonical artifact paths, the portable state, brief, complete proposed Specs, and continuation; compat Runtime state is reported as migration-required. Fill command-template placeholders before executing NEXT commands."},check:{usage:"comet native check <change-name>",purpose:"Compatibility guidance for running checks through Agent platform tools.",output:"For current changes, run comet native status <change-name> --json and follow the continuation to dispatch verification through comet native next."},status:{usage:"comet native status [<change-name>] [--cursor <token>] [--details]",purpose:"Discover portable stable boundaries, parent child readiness, or the exact next Runner action.",options:["--cursor <token> Continue a status-list page, or a named details/history page.","--details SDK: include complete business state and Action/Wait history. Compat: include one fixed-size detail page."],output:"SDK status includes the exact continuation, claim request templates, all pending/running/unknown work, and the latest 12 settled records per history collection. run.history reports omitted records; --details returns complete history without --cursor. Compat status reports business continuation and details use --cursor for fixed-size pages; parent changes expose childSummary and readyChildren.",examples:["comet native status --json","comet native status session-timeout --details --json"]},select:{usage:"comet native select <change-name> [--rebind]",options:["--rebind Explicitly bind the same idle SDK Run to the current Git branch; preserve work and approvals, and reject unresolved executions."],purpose:"Select one Native change after validating its workspace binding.",output:"The selected change record."},next:{usage:`comet native next <change-name> --session <actual-session> [--action <id>] [--result <json-file>] [--review current-session|independent] [--accept-on-pass <authorization-summary>] [--details]
|
|
432
|
+
comet native next <change-name> --summary <text> [--coordination-mode multi-session|single-session] [--max-parallel <n>] [--expected-state-version <n>] [--expected-action <action>]
|
|
433
|
+
comet native next <change-name> --summary <text> [--confirmed|--accept-result|--revise-implementation|--revise-requirements|--retry-verifier|--resolve-verifier-blocker] [--expected-state-version <n>] [--expected-action <action>]
|
|
434
|
+
comet native next <sdk-change> --confirmed --coordination-mode multi-session|single-session --summary <text> --expected-state-version <n> --expected-action confirm-shape
|
|
435
|
+
comet native next <sdk-change> --accept-result|--revise-implementation|--retry-verifier|--continue-builder|--resolve-verifier-blocker --summary <text> --proposal-hash <hash> --expected-state-version <n> --expected-action <action>
|
|
436
|
+
comet native next <change-name> --runner-input <json-file> [--validate-only]`,purpose:"Advance SDK-owned Runtime actions and bound user decisions, or recover a compat Runtime Agent boundary and use its skill-coordinated Builder/Verifier JSON bridge.",options:["--session <actual-session> Claim a new ordinary SDK task using its real receiving session.","--action <id> Preserve the current task ID when claiming or reporting.","--result <json-file> Submit actual status/output business fields, run authorized internal steps, and return the next task. Requires --action and --session.","--review current-session|independent Continue ordinary Verify in this session or leave it for a separate actual receiver. Honor explicit user requests for independent review.","--accept-on-pass <authorization-summary> With this Verify result only, record prior explicit user delegation to accept and archive if all criteria pass. Without this option, wait for user acceptance.","--details With --session, include the full SDK projection alongside the current task.","--summary <text> Required transition or recovery summary.","--confirmed Confirm the persisted Shape boundary with both expected guards, or confirm an explicitly degraded verifier-unavailable fallback before Archive.","--coordination-mode multi-session|single-session Choose how a multi-child Supervisor proceeds. Supply it with --confirmed at the persisted Shape boundary to confirm the full plan and mode together, or select it during preparation and confirm the plan afterward.","--accept-result Accept the current skill-coordinated Verify result and make it archive-ready.","--finish keep|merge|push|pull-request For compat changes, with --accept-result record the explicitly chosen isolated-workspace finish in the same guarded decision. SDK Runs keep Git delivery separate.","--revise-implementation Keep confirmed requirements unchanged and return Verify to Build for implementation revision.","--revise-requirements Renew a pending Shape proposal or return Verify, Archive, or a quiescent SDK Supervisor Build to Shape. SDK changes also allow revising after an ordinary Builder explicitly failed; use the current continuation proposal hash. Preserve partial work and reconcile running/unknown Actions first. The new Shape still requires explicit approval. Completed SDK Runs require an application-validated blocked Child recovery.","--retry-verifier Retry a failed or unavailable Verifier when the continuation allows it.","--continue-builder After a failed SDK Builder Action, explicitly continue from its preserved workspace in a new Action.","--resolve-verifier-blocker Resume an SDK or compat blocked Verifier with the retained candidate and valid checks; a completed SDK Supervisor Child resumes with a new Builder. SDK recovery requires the current proposal hash and both expected guards; original outcomes are preserved.","--max-parallel <n> Compat-only Supervisor concurrency override. SDK and Compat use native.max_parallel_children (default 2); configure it in project settings or .comet/config.yaml; single-session always uses 1.","--expected-state-version <n> Continuation-issued guard that rejects stale public transition decisions.","--expected-action <action> Continuation-issued guard that binds the public transition decision to its intended action.","--proposal-hash <hash> SDK decision guard from the current Wait or blocked Child continuation; required with --accept-result, --revise-implementation, --retry-verifier, --continue-builder, or --resolve-verifier-blocker, and with --revise-requirements for pending Shape or failed ordinary Builder recovery.","--runner-input <file> Skill-coordinated JSON: builder-handoff, dispatch-verifier, retry-checks, verifier-response, verifier-started, verifier-execution-error, or verifier-unavailable. Builder/dispatch identity fields are rejected; verifier responses must echo the current candidateId and verifierExecutionRef from the Verifier dispatch.","--validate-only Validate the Runner JSON shape and current boundary without writing state or starting a process; requires --runner-input."," Choose one object template from an inputOptions exclusiveGroup and save it as UTF-8 JSON (BOM accepted). Field errors return issues with JSON pointer, missingFields and unknownFields. Execute agent.continuation in agent.workspace.cwd; Supervisor results use task.returnAction."," builder-handoff fields: kind, summary, addressed_acceptance_ids, acceptance_review, checks, known_limits, optional review. Cover every confirmed acceptance ID with its actual status, evidence and note. Only implemented-with-evidence entries with nonempty evidence are ready for handoff. checks contain actual Agent platform reports. An optional review records status=passed, summary and reviewer_execution_ref from a separate read-only review."," dispatch-verifier fields: kind. Run development checks through Agent platform tools and hand the current candidate to the selected Verifier."," retry-checks is a retired compatibility input that returns platform execution guidance without running a command."," verifier-response fields: kind, candidateId, verifierExecutionRef, response (final-result). Copy the current candidate and receiving session from the dispatch and report every acceptance item."," verifier-started is optional compatibility progress reporting for the existing Verifier session; it does not supervise a process or authorize completion."," verifier-execution-error fields: kind, summary, stateVersion, iteration, attempt, verifierExecutionRef copied from verifierDispatch."," verifier-unavailable fields: kind, summary, stateVersion, iteration, attempt, verifierExecutionRef. Record the actual platform capability failure; it never grants a passing result."," Supervisor task fields: supervisor-builder-result (child, runId, candidateCommit), supervisor-builder-failure (child, runId, reason), supervisor-verifier-result (child, runId, verdict, verification data), supervisor-reconnect (child, runId), supervisor-cancel (child, runId, reason), or supervisor-integrate (child, checks)."," supervisor-checks is retired and returns platform execution guidance without starting a process or generating a receipt."," supervisor-verifier-result evidence fields: summary, checks (actual platform reports), acceptance [{id,result,reason}]. verdict is pass, fail or blocked; every task acceptance ID must appear exactly once."," supervisor-integrate fields: child, integrationCommit and checks [{name,status,reason}], reporting the actual merge and platform checks."],output:"SDK-owned changes return the current Run Action or Wait and the same continuation as status/show, including current decision guards and pending Action claimRequest templates. Fill the template with the host session and claim token; the successful claim returns the current Action input. Authorized internal business steps and Archive continue from the original Run. Builder and Verifier handoffs use `comet runtime dispatch --application native`; never resubmit running/unknown work. Compat Runtime changes return the portable state, Runner result, continuation.inputOptions, and userCommunication. The compat JSON bridge is not trusted identity attestation: a passing skill-coordinated result waits for explicit user confirmation before Archive.",examples:['comet native next session-timeout --summary "Shape confirmed" --confirmed --expected-state-version <n> --expected-action confirm-shape','comet native next session-timeout --summary "Current result accepted" --accept-result','comet native next session-timeout --summary "Implementation needs revision" --revise-implementation','comet native next session-timeout --summary "Acceptance criteria changed" --revise-requirements','comet native next session-timeout --revise-requirements --summary "User changed the pending Shape or stopped Builder requirements" --proposal-hash <hash> --expected-state-version <n> --expected-action revise-requirements','comet native next session-timeout --summary "Retry verifier infrastructure" --retry-verifier','comet native next session-timeout --continue-builder --summary "Continue the inspected partial work" --proposal-hash <hash> --expected-state-version <n> --expected-action continue-builder','comet native next session-timeout --summary "Retry semantic verification" --resolve-verifier-blocker',"comet native next session-timeout --runner-input <temporary-json-file>"]},cancel:{usage:"comet native cancel <change-name> [--reason <text>] [--dry-run]",purpose:"Cancel an unfinished SDK Native change: it stops counting as active without verification or a fake Archive.",options:["--reason <text> Record why the change is cancelled; defaults to a neutral user-cancellation note.","--dry-run List what cancellation would stop, release, and retain without changing any state."],output:"The cancellation status and its outstanding acknowledgements. Code, commits, branches, and the workspace are always retained; deleting implementations or worktrees stays a separate explicit Git operation. Completed changes are rejected in favor of archive; legacy 0.4 runtime changes keep their original lifecycle."},archive:{usage:`comet native archive <change-name> --dry-run [--finish merge|push|pull-request|keep] [--commit-message <text>] [--merge-message <text>]
|
|
437
|
+
comet native archive <change-name> [--confirmed] [--serial-first <current-change>] [--commit-message <text>] [--merge-message <text>]
|
|
438
|
+
comet native archive <sdk-change-name> --recover [--legacy-spec-backup <json-file>]`,purpose:"Preview or execute deterministic Archive after the portable state reaches archive-ready.",options:["--dry-run Run the complete read-only Archive and workspace-finish readiness check; it persists only an explicit --finish choice.","--finish <action> Persist merge, push, pull-request, or keep for an isolated workspace.","--expected-state-version <n> Preserve this continuation-issued guard when confirming a new finish choice; stale choices are rejected before it is recorded.","--commit-message <text> For compat changes, set the archive commit message; Unicode and multiline text are supported. Git hooks still run.","--merge-message <text> For compat changes, set the local merge commit message; requires merge finish. Omit it to use Git defaults.","--serial-first <current-change> During execution only, confirm that this change archives before detected capability peers; the value must equal <change-name>.","--confirmed Confirm Archive when project policy requires it.","--legacy-spec-backup <json-file> SDK only: read a bounded original-Spec backup for an existing legacy Archive transaction. Use a new file outside the project so it does not change the old candidate. Requires exact schema/runId/transactionId/path/hash and original candidate digest matches; never writes the source file or Git index. See docs/operations/native-archive-recovery.zh.md.","--recover For an SDK-owned change, reconcile one unknown Supervisor delivery, Archive, or cleanup Action only after confirming the original execution process has stopped; never retry it as new work."],output:"Readiness, every blocker, actual prepared commitMessages (mergeMessage is null when no merge is planned), and the exact next continuation, or the completed Archive transaction and workspace finish result. Messages are retained for retries. After a Git hook rejects a message, provide a corrected message with --confirmed for the unfinished step; completed commits are never rewritten. Execute the returned confirmed command only after ready is true; Archive does not repeat verification."},doctor:{usage:"comet native doctor [<change-name>] [--repair] [--confirmed] [--migrate-history]",purpose:"Inspect Native business state and existing transactions, or recover the original Run checkpoint.",options:["--repair Apply deterministic migration or rebuild from the portable stable boundary.","--migrate-history Validate and close built-in Native terminal Runs whose business cleanup is complete. Preserve documents and checkpoints; unfinished or invalid Runs remain active. Safe to rerun after interruption. Upgrade CLI and platform Hooks together: older Runtime versions cannot write the new storage format. Ordinary inspection never migrates.","--confirmed With --repair and a named managed change whose local Run history is missing, recover its saved Run checkpoint. Original business approvals and task claims are preserved."],output:"Health, original business records, and structured recovery with diagnosticArgs, recoveryArgs and preconditions. Inspection does not change the Run."},transfer:{usage:`comet native transfer export <change-name> --output <directory> --confirmed-stopped
|
|
439
|
+
comet native transfer import --input <directory>`,purpose:"Carry a prepared Supervisor Child Builder and its Git worktrees to another checkout before handing the next Child task to an Agent.",subcommands:["export Snapshot the parent checkpoint, Supervisor branches, and non-ignored uncommitted work.","import Validate the package and restore its Run and worktrees in a checkout at the same target commit."],options:["--output <directory> New private directory for the transfer package; must not already exist.","--input <directory> Existing transfer package to import.","--confirmed-stopped Confirm the original Builder and other Supervisor agents stopped before export."],output:"The package path or restored change and worktree paths. An in-flight Builder becomes outcome-unknown and must be reconciled; import never reports its work as completed."}});function rv(e,t){return`${e}:
|
|
440
|
+
${t.map(r=>` ${r}`).join(`
|
|
441
|
+
`)}`}function v8(e){let t=e.filter(n=>n!=="--help");if(t.length===0)return"";let r=t.slice(0,2).join(" ");return MN[r]||t.length>1&&MN[t[0]]?.subcommands?r:t[0]}function w8(e=[]){let t=v8(e),r=MN[t];if(!r)throw new Error(`Unknown Native help topic: ${t}`);let n=[`Usage: ${r.usage}`,"",r.purpose];r.agentQuickStart&&n.push("",rv("Agent Quick Start",r.agentQuickStart)),r.subcommands&&n.push("",rv("Commands",r.subcommands));let i=t===""?r.options:[...r.options??[],...wB];return i&&i.length>0&&n.push("",rv("Options",i)),n.push("",`Output:
|
|
442
|
+
${r.output}`),r.examples&&n.push("",rv("Examples",r.examples)),t===""&&n.push("","Run `comet native <command> --help` for command-specific details."),{topic:t,usage:`${n.join(`
|
|
443
|
+
`)}
|
|
444
|
+
`}}var y8=w8().usage;var sn=class extends Error{};function Na(e,t){let r=e.flatMap((n,i)=>n===t?[i]:[]);if(r.length>1)throw new sn(`${t} may only be provided once`);return r.length===0?!1:(e.splice(r[0],1),!0)}function _l(e,t){let r=e.flatMap((o,a)=>o===t?[a]:[]);if(r.length>1)throw new sn(`${t} may only be provided once`);if(r.length===0)return;let n=r[0],i=e[n+1];if(i===void 0||i.startsWith("--"))throw new sn(`${t} requires a value`);return e.splice(n,2),i}function kB(e){if(e.length>0)throw new sn(`Unexpected argument: ${e[0]}`)}function FN(e,t){let r=Of.normalize(yB(e)),n=Of.normalize(yB(t));return process.platform==="win32"?r.toLowerCase()===n.toLowerCase():r===n}function yB(e){let t=Of.resolve(e);try{return k8.native(t)}catch{return t}}function b8(e,t){let r=Of.resolve(t,e),n=ue(t);if(!n.isSecondaryWorktree||n.currentWorktreeRoot===null||n.primaryWorktreeRoot===null)return r;let i=ue(r);return!i.isGitWorktree||i.currentWorktreeRoot===null||i.primaryWorktreeRoot===null||!FN(n.primaryWorktreeRoot,i.primaryWorktreeRoot)||FN(n.currentWorktreeRoot,i.currentWorktreeRoot)?r:FN(t,n.currentWorktreeRoot)?Of.resolve(t):n.currentWorktreeRoot}async function bB(e,t=process.cwd()){return e?b8(e,t):Ck(t)}function AB(e,t){return e==="status"||e==="show"||e==="root"&&t[0]==="show"}async function RB(e){let t=await Te(e);return we(e,t?.native.artifact_root??"docs")}function NB(e){return JSON.stringify(e,null,2)+`
|
|
445
|
+
`}function Qi(e,t,r){return{command:e,exitCode:0,data:t,text:r??NB(t)}}function A8(e,t){if(t instanceof Cl)return{command:e,exitCode:65,data:{change:t.change,findings:t.findings},error:{code:"document-invalid",message:t.message}};if(t instanceof Zo)return{command:e,exitCode:65,data:{builderReadiness:{ready:!1,missingIds:t.missingIds,incompleteIds:t.incompleteIds}},error:{code:"invalid-data",message:t.message}};if(t instanceof Fu)return{command:e,exitCode:65,error:{code:"invalid-data",message:t.message,issues:t.issues}};if(t instanceof sn)return{command:e,exitCode:64,error:{code:"usage",message:t.message}};if(t instanceof Uh)return{command:e,exitCode:73,data:{capability:t.capability,expectedHash:t.expectedHash,actualHash:t.actualHash,canonicalPath:t.canonicalPath},error:{code:"conflict",message:t.message}};if(t instanceof ws)return{command:e,exitCode:73,data:{change:t.change,expectedRevision:t.expectedRevision,actualRevision:t.actualRevision,outcome:"revision-conflict"},error:{code:"conflict",message:t.message}};if(t instanceof ys)return{command:e,exitCode:73,data:{requestedIsolation:t.requestedIsolation,activeChanges:t.activeChanges,requiredAction:"create-native-worktree"},error:{code:"workspace-isolation-required",message:t.message}};if(t instanceof $i)return{command:e,exitCode:73,data:{preparation:t.preparation},error:{code:"workspace-preparation-incomplete",message:t.message}};if(t instanceof Pg)return{command:e,exitCode:65,data:t.recovery,error:{code:"implementation-scope-stale",message:t.message}};if(t instanceof Error){let r=t.code;if(r&&new Set(["EACCES","EPERM","EIO","EMFILE","ENFILE","ENOSPC","EROFS"]).has(r))return{command:e,exitCode:70,error:{code:"internal",message:t.message}};let n=/\b(lock|transaction|conflict|occupied|incomplete|recovery)\b/iu.test(t.message);return{command:e,exitCode:n?73:65,error:{code:n?"conflict":"invalid-data",message:t.message}}}return{command:e,exitCode:70,error:{code:"internal",message:String(t)}}}function SB(e,t){let r=A8(e,t),n=r.error;if(!n)return r;let i=O$({code:n.code,message:n.message,data:r.data});return i?{...r,envelope:i}:r}function R8(e,t,r=!1){let n=e.envelope??T$(e.data);return t?{exitCode:e.exitCode,stdout:JSON.stringify({command:e.command,exitCode:e.exitCode,agent:N$(e.data,e.executionCwd),...n===void 0?{}:{summary:n.summary,...n.next===void 0?{}:{next:n.next},...n.user_message===void 0?{}:{user_message:n.user_message}},...e.data===void 0?{}:{data:e.data},...e.error===void 0?{}:{error:e.error}})+`
|
|
446
|
+
`}:e.error?{exitCode:e.exitCode,stderr:n?C$(n,e.error.message,r?e.data:void 0):e.error.message}:n?{exitCode:e.exitCode,stdout:E$(n,r?e.data:void 0)}:r&&e.text!==void 0&&e.data!==void 0&&e.text!==NB(e.data)?{exitCode:e.exitCode,stdout:`${e.text}
|
|
447
|
+
${Mi.details}
|
|
448
|
+
${JSON.stringify(e.data,null,2)}
|
|
449
|
+
`}:{exitCode:e.exitCode,stdout:e.text}}function N8(e,t,r=!1){let n=R8(e,t,r),i=!1;if(n.stdout?.trim())try{let o=JSON.parse(n.stdout);i=!!o&&typeof o=="object"&&!Array.isArray(o)}catch{i=!1}return{output:n,structuredDataVisible:i}}function EB(e,t,r=!1){return N8(e,t,r).output}Xo();Ni();Qc();ze();Rl();lr();lt();Et();St();He();Se();Ft();Ff();Hv();import{promises as KW}from"node:fs";import Uf from"node:path";ze();lr();dt();ul();Hi();Et();St();Ff();Ft();Se();He();import W5 from"node:path";fv();ze();or();import{AsyncLocalStorage as _5}from"node:async_hooks";VA();import{createHash as I5,randomUUID as Uke}from"node:crypto";import DW from"node:path";Ak();import{promises as Qv}from"node:fs";import YS from"node:path";async function jW(e,t){let r=bk(e),n=YS.join(r.workspaceRoot,"observability"),i=r.dataRoot;for(let a of["","workspaces",r.workspaceId,"observability"]){i=YS.join(i,a);let s;try{s=await Qv.lstat(i)}catch(c){if(!t||c.code!=="ENOENT")throw c;await Qv.mkdir(i,{recursive:a===""}).catch(l=>{if(l.code!=="EEXIST")throw l}),s=await Qv.lstat(i)}if(!s.isDirectory()||s.isSymbolicLink())throw new Error("Runtime 统计目录必须是普通目录")}let o=YS.join(n,"performance.sqlite");for(let a of["","-wal","-shm"])try{let s=await Qv.lstat(o+a);if(!s.isFile()||s.isSymbolicLink()||s.size>64*1024*1024)throw new Error("Runtime 统计文件无效")}catch(s){if(s.code!=="ENOENT")throw s}return o}import{stripVTControlCharacters as C5}from"node:util";function $W(e,t=process.env){let r=C5(e).replace(/(Bearer\s+)[^\s"']+/giu,"$1[redacted]").replace(/((?:api[_-]?key|auth[_-]?token|access[_-]?token|_authToken|password|secret)\s*[=:]\s*["']?)[^\s"',}]+/giu,"$1[redacted]").replace(/(https?:\/\/[^\s/:]+:)[^\s@]+@/giu,"$1[redacted]@");for(let[n,i]of Object.entries(t))i&&i.length>=6&&/key|token|password|secret|credential/iu.test(n)&&(r=r.split(i).join("[redacted]"));return r}var x5=864e5,P5=1e4,BW=new _5;function XS(e){let t=BW.getStore();t&&t.binding.workflow===e.workflow&&(!t.binding.runId||t.binding.runId===e.runId)&&Object.assign(t.binding,e)}function Hf(e,t){return $W(e).slice(0,t)}async function WW(e,t){if(!t.length)return;let r=BW.getStore();if(r){let i=o=>process.platform==="win32"?DW.resolve(o).toLowerCase():DW.resolve(o);if(i(e)===i(await r.projectRoot())){r.spans.push(...t);return}}let n=Sh(await jW(e,!0));try{n.exec(`PRAGMA busy_timeout=25; PRAGMA journal_mode=WAL;
|
|
450
|
+
CREATE TABLE IF NOT EXISTS trace_spans (
|
|
451
|
+
id TEXT PRIMARY KEY, trace_id TEXT NOT NULL, workflow TEXT NOT NULL,
|
|
452
|
+
change_name TEXT NOT NULL, run_id TEXT NOT NULL, span_id TEXT NOT NULL,
|
|
453
|
+
parent_span_id TEXT, kind TEXT NOT NULL, name TEXT NOT NULL, status TEXT NOT NULL,
|
|
454
|
+
started_at TEXT, ended_at TEXT, updated_at TEXT NOT NULL,
|
|
455
|
+
revision INTEGER NOT NULL, data TEXT NOT NULL);
|
|
456
|
+
CREATE INDEX IF NOT EXISTS trace_spans_time ON trace_spans(updated_at);
|
|
457
|
+
CREATE INDEX IF NOT EXISTS trace_spans_trace ON trace_spans(trace_id);
|
|
458
|
+
BEGIN IMMEDIATE;`);let i=n.prepare(`INSERT INTO trace_spans VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)
|
|
459
|
+
ON CONFLICT(id) DO UPDATE SET status=CASE WHEN excluded.revision >= trace_spans.revision THEN excluded.status ELSE trace_spans.status END,
|
|
460
|
+
started_at=COALESCE(trace_spans.started_at,excluded.started_at),
|
|
461
|
+
ended_at=CASE WHEN excluded.revision < trace_spans.revision THEN trace_spans.ended_at
|
|
462
|
+
WHEN excluded.status IN ('running','pending','waiting','unknown') THEN NULL
|
|
463
|
+
ELSE COALESCE(trace_spans.ended_at,excluded.ended_at) END, updated_at=MAX(trace_spans.updated_at,excluded.updated_at),
|
|
464
|
+
revision=MAX(trace_spans.revision,excluded.revision),
|
|
465
|
+
data=CASE WHEN excluded.revision >= trace_spans.revision THEN excluded.data ELSE trace_spans.data END
|
|
466
|
+
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 s={...a,name:Hf(a.name,240),summary:a.summary?Hf(a.summary,1e3):void 0,attributes:Object.fromEntries(Object.entries(a.attributes??{}).slice(0,20).map(([u,f])=>[Hf(u,80),Array.isArray(f)?f.slice(0,30).map(d=>Hf(d,240)):typeof f=="string"?Hf(f,2e3):f]))};t.length>1e3&&a.parentSpanId===null&&(s.attributes.truncated=!0);let c=JSON.stringify(s);for(;Buffer.byteLength(c,"utf8")>4096;){let u=Object.keys(s.attributes).reverse().find(f=>f!=="truncated");if(u)delete s.attributes[u];else if(s.summary)s.summary=s.summary.slice(0,Math.floor(s.summary.length*.75));else break;c=JSON.stringify(s)}if(Buffer.byteLength(c,"utf8")>4096)continue;let l=I5("sha256").update(JSON.stringify([a.traceId,a.spanId])).digest("hex");i.run(l,a.traceId,a.workflow,a.change,a.runId,a.spanId,a.parentSpanId,a.kind,s.name,a.status,a.startedAt,a.endedAt,a.updatedAt,a.revision,c)}n.prepare("DELETE FROM trace_spans WHERE updated_at < ?").run(new Date(Date.now()-7*x5).toISOString()),n.prepare("DELETE FROM trace_spans WHERE id IN (SELECT id FROM trace_spans ORDER BY updated_at DESC, id DESC LIMIT -1 OFFSET ?)").run(P5),n.exec("COMMIT")}finally{n.close()}}var T5=(e,t)=>`workflow:${e}:${t}`,qW=(e,t)=>{let r=e.split(".");return t==="classic"&&["full","hotfix","tweak"].includes(r[0])?r[1]??r[0]:r[0]},LW=e=>({runId:e.runId,revision:e.revision,status:e.status,actions:e.actions.map(t=>({id:t.id,attempt:t.attempt,status:t.status,reason:t.reason,...t.outcome?{outcome:{outcomeId:t.outcome.outcomeId,summary:t.outcome.summary}}:{}})),waits:e.waits.map(t=>({id:t.id,status:t.status})),evidenceWaits:e.evidenceWaits?.map(t=>({id:t.id,status:t.status}))}),VW=e=>e&&typeof e=="object"?Array.isArray(e)?[`${e.length} items`]:Object.keys(e).slice(0,30):[e===null?"null":typeof e];function O5(e){let{workflow:t,previous:r,next:n,initial:i,observedAt:o}=e,a=T5(t,n.runId),s=`run:${n.runId}`,c={workflow:t,change:n.runId,runId:n.runId,traceId:a,updatedAt:o,revision:n.revision},l=["completed","failed","cancelled"].includes(n.status),u=new Map(r?.actions.map(d=>[`${d.id}:${d.attempt}`,d])),f=[{...c,spanId:s,parentSpanId:null,kind:"workflow",name:n.workflow.id,status:n.status==="completed"?"succeeded":n.status,startedAt:i?o:null,endedAt:l&&(i||r!==null&&r.status!==n.status)?o:null,summary:n.reason,attributes:{workflowVersion:n.workflow.version,sequence:n.sequence,parentRunIds:n.lineage,childRunIds:n.children.map(d=>d.runId)}}];for(let d of n.actions){let p=u.get(`${d.id}:${d.attempt}`);if(p&&p.status===d.status&&p.outcome?.outcomeId===d.outcome?.outcomeId&&p.reason===d.reason&&p.outcome?.summary===d.outcome?.summary)continue;let m=["succeeded","failed","cancelled"].includes(d.status);f.push({...c,spanId:`action:${d.id}:${d.attempt}`,parentSpanId:s,kind:"action",name:d.stepId,status:d.status,attempt:d.attempt,startedAt:d.status==="running"&&(p?.status==="pending"||i)?o:null,endedAt:m&&(i||r!==null)?o:null,summary:d.outcome?.summary??d.reason,attributes:{phase:qW(d.stepId,t),actionId:d.id,actionType:d.type,ref:d.ref??null,executor:d.claim?.executorId??null,inputFields:VW(d.input),outputFields:d.outcome?VW(d.outcome.output):[],artifacts:(d.outcome?.artifacts??[]).map(h=>h.uri)}})}for(let d of["wait","evidence"]){let p=d==="wait"?n.waits:n.evidenceWaits??[],m=d==="wait"?r?.waits:r?.evidenceWaits,h=new Map(m?.map(g=>[g.id,g]));for(let g of p){let v=h.get(g.id);v?.status!==g.status&&f.push({...c,spanId:`${d}:${g.id}`,parentSpanId:s,kind:d,name:g.stepId,status:g.status==="pending"?"waiting":g.status==="resolved"?"succeeded":g.status==="cancelled"?"cancelled":"unknown",startedAt:!v&&(r!==null||i)&&g.status==="pending"?o:null,endedAt:g.status!=="pending"&&(i||r!==null)?o:null,attributes:{phase:qW(g.stepId,t),waitId:g.id,decision:"decision"in g?g.decision?.choice??null:null}})}}return f}function MW(e,t,r){let n=null;return{...r,...r.restoreCheckpoint?{restoreCheckpoint:(i,o,a)=>r.restoreCheckpoint(i,o,a)}:{},async read(i){let o=await r.read(i);try{n=o?LW(o):null}catch{n=null}return o&&XS({workflow:t,change:o.runId,runId:o.runId}),o},async compareAndSwap(i,o,a){let s=n?.runId===i&&n.revision===o?n:null,c=await r.compareAndSwap(i,o,a);if(c){XS({workflow:t,change:i,runId:i});try{await WW(e,O5({workflow:t,previous:s,next:a,initial:o===null,observedAt:new Date().toISOString()}))}catch{}try{n=LW(a)}catch{n=null}}return c}}}or();var QW=dr(Ur(),1);Qc();import{promises as rE}from"node:fs";import{isDeepStrictEqual as eE}from"node:util";import Ca from"node:path";Es();Ff();yv();Hv();ze();lr();wa();or();Eo();St();He();fv();Pl();Se();import FW from"node:path";async function zs(e){let t=e.run.input;if(typeof t?.artifactRootRef!="string"||!Number.isSafeInteger(e.run.revision)||(await Fe(e.projectRoot,"native",e.run.runId,{readOnly:!0}))?.application!=="native")return!1;if(await ht({singleWriter:!0,rootDir:FW.join(Le(e.projectRoot),"sdk-runs","native")}).readDisposition(e.run.runId)==="closed")return ZS(e);let i=await we(e.projectRoot,t.artifactRootRef,{readOnly:!0});return $e(i,()=>ZS(e))}async function ZS(e){let{projectRoot:t}=e,r=await Fe(t,"native",e.run.runId,{readOnly:!0});if(!r||r.application!=="native")return!1;let n=ht({singleWriter:!0,rootDir:FW.join(Le(t),"sdk-runs","native")}),i=await n.read(r.runId);if(!i||i.revision!==e.run.revision||!["cancelled","completed"].includes(i.status))return!1;let o=KS(null),a=Ea(i,o.workflow,o.transitionHandler),s=Ea(e.run,o.workflow,o.transitionHandler);if(D(a)!==D(s))throw new Error("Native Run content changed at the same revision before history closure");if(!wv(o.workflow,a))throw new Error("Native history requires a known built-in workflow definition");let c=await wr({...o,workflows:[o.workflow],transitionHandlers:[o.transitionHandler],store:{read:async()=>a,compareAndSwap:async()=>!1}}).inspect(r.runId),l=M(c.state),u=c.input;if(c.runId!==r.change||c.workflow.id!=="comet-native"||l.name!==r.change||u?.name!==r.change||typeof u.artifactRootRef!="string")throw new Error("Native history Run does not match its change ownership");if(await n.readDisposition(c.runId)==="closed")return await Cg(t,r),!0;if(c.ready.length>0||c.waits.some(f=>f.status==="pending")||c.evidenceWaits?.some(f=>f.status==="pending"))return!1;if(c.status==="cancelled"){if((await So({projectRoot:t,run:c}))?.status!=="cancelled")return!1}else{if(!l.archived||l.phase!=="archive"||l.status!=="done"||!(await Rf({projectRoot:t,run:c})).quiescent)return!1;let f=await an(t);if(f.status==="selected"&&f.selection.workflow==="native"&&f.selection.change===c.runId)return!1;let d=c.outputs["archive.execute"]?.value,p=c.outputs["archive.finalize"]?.value;if(!d||typeof d.archiveRef!="string"||typeof d.transactionId!="string"||d.stateVersion!==l.state_version-1||!p)return!1;let m=await we(t,u.artifactRootRef,{readOnly:!0}),h=await jl({paths:m,state:l,runId:c.runId,archiveRef:d.archiveRef,history:!0,allowMissingReport:["3","4"].includes(c.workflow.version),verificationResultHash:c.workflow.version!=="1"?xB(l):void 0});if(h.transactionId!==d.transactionId||D(p)!==D(h))throw new Error("Native history Archive receipt does not match its committed outcome")}return e.recover&&await n.readDisposition(c.runId)==="reopening"?(await _g(t,"native",c.runId),await n.reopenRun(c.runId,c.revision)?ZS({projectRoot:t,run:c}):!1):!await n.closeRun(c.runId,c.revision)||await n.readDisposition(c.runId)!=="closed"?!1:(await Cg(t,r),!0)}lr();wa();St();He();Eo();async function Uv(e){if(e.run.status!=="cancelled")return;let t=e.run.input?.artifactRootRef;if(typeof t=="string"){let o=await we(e.projectRoot,t);if(await Mn(o,{kind:"archive",change:e.run.runId}))return}let r=await So(e);if(!r?.quiescent)return;if(!r.cleanupRequired){await zs(e);return}let n=e.run.input;if(typeof n?.artifactRootRef!="string")return;let i=await we(e.projectRoot,n.artifactRootRef);await $e(i,async()=>{let o=await an(e.projectRoot);if(o.status!=="selected"||o.selection.change!==e.run.runId)return;let a=await Fe(e.projectRoot,"native",e.run.runId);a&&(a.application==="native"?o.selection.workflow==="native":o.selection.workflow==="application"&&o.selection.applicationId===a.application)&&await js(e.projectRoot,o.selection.workflow,e.run.runId)}).catch(o=>{throw new Error(`Native cancellation is committed but current selection release remains pending. Inspect the unfinished workspace transaction with comet native doctor --json, then retry comet native doctor ${e.run.runId} --repair. ${o instanceof Error?o.message:String(o)}`,{cause:o})}),await zs(e)}async function HW(e){let{projectRoot:t,store:r,runId:n,expectedRevision:i,next:o}=e;if(o.status!=="cancelled")throw new Error("Native cancellation commit requires a cancelled Run");let a=o.input;if(typeof a?.artifactRootRef!="string")throw new Error("Native cancellation commit requires its artifact root");let s=await we(t,a.artifactRootRef);return $e(s,async()=>{let c=await r.read(n);if(c&&c.status!=="cancelled"){if(await Mn(s,{kind:"archive",change:n}))throw new Error(`Native Archive transaction must finish before cancellation; run comet native archive ${n} or recover its original Action with --recover`);if(c.actions.some(l=>l.stepId.startsWith("archive.")&&["running","unknown"].includes(l.status)))throw new Error(`Native Archive execution must finish or recover before cancellation; run comet native archive ${n} --recover`)}return r.compareAndSwap(n,i,o)},{allowedPortableTransaction:{kind:"archive",change:n}})}lr();wa();St();He();async function Jv(e){if(e.run.status!=="completed")return;let t=e.run.input;if(typeof t?.artifactRootRef!="string")return;let r=await we(e.projectRoot,t.artifactRootRef);await $e(r,async()=>{let n=await an(e.projectRoot);if(n.status!=="selected"||n.selection.change!==e.run.runId)return;let i=await Fe(e.projectRoot,"native",e.run.runId);i&&(i.application==="native"?n.selection.workflow==="native":n.selection.workflow==="application"&&n.selection.applicationId===i.application)&&await js(e.projectRoot,n.selection.workflow,e.run.runId)}).catch(n=>{throw new Error(`Native SDK Run ${e.run.runId} is archived but current selection release remains pending. Inspect the unfinished workspace transaction with comet native doctor --json, then retry comet native doctor ${e.run.runId} --repair. ${n instanceof Error?n.message:String(n)}`,{cause:n})}),await zs(e)}Er();it();ze();lr();lt();Et();dt();He();Se();Ft();Ft();rn();Mf();ze();var tE=class extends Error{constructor(r,n,i=!1,o){let a=o?["runtime","dispatch","--application-file",Ca.join(o.packageRoot,"application.json"),"--project-root",r,"--request","<recovery-request.json>","--json"]:null;super(a?`Native SDK Run ${n} needs checkpoint recovery. Save the recovery request JSON to a file and replace <recovery-request.json> with its path. Run comet with the exact argument array below to restore the recorded state and advance only the Runtime, without executing host work.
|
|
467
|
+
Recovery argv: ${JSON.stringify(a)}
|
|
468
|
+
Recovery request: ${JSON.stringify({operation:"next",runId:n})}`:`Native SDK Run ${n} needs checkpoint recovery; run comet native doctor ${n} --repair${i?"":" --confirmed"} before continuing`);this.projectRoot=r;this.change=n;this.interrupted=i}projectRoot;change;interrupted;code="NATIVE_SDK_RUN_RECOVERY_REQUIRED"};function j5(e){return e.revision===1||["completed","cancelled","failed"].includes(e.status)||e.state.phase==="shape"&&e.waits.some(t=>["shape.confirm","supervisor.shape.confirm"].includes(t.stepId)&&t.status==="resolved"&&t.decision?.choice==="rejected")||e.waits.some(t=>t.status==="pending")||e.evidenceWaits?.some(t=>t.status==="pending")?!0:e.actions.some(t=>["pending","running","unknown"].includes(t.status)&&(t.type==="invoke_skill"||t.type==="handoff"||!!t.claim?.sessionId||!["shape.prepare","shape.revalidate","verify.revalidate","archive.prepare"].includes(t.stepId)))}function $5(e,t){return JSON.stringify(e)===JSON.stringify(t)}function D5(e,t,r){if(e.actions.some(s=>s.stepId==="supervisor.cleanup"&&s.status==="succeeded"))return;let i=e.actions.filter(s=>s.status==="succeeded"&&["supervisor.prepare","supervisor.child.prepare"].includes(s.stepId));if(i.length===0)return;let o=Yt(r),a=!t.archived;for(let s of i){let c=s.outcome?.output;if(!c||typeof c!="object"||Array.isArray(c))throw new Error("Native SDK Supervisor worktree receipt is invalid");let l=c,u=s.stepId==="supervisor.child.prepare"?l.child:null;if(s.stepId==="supervisor.child.prepare"&&typeof u!="string")throw new Error("Native SDK Supervisor Child worktree receipt is invalid");let f=typeof u=="string"?zt(r,t.name,u):It(r,t.name),d=typeof u=="string"?l.worktree:l.integrationWorktree,p=typeof u=="string"?l.branch:l.integrationBranch;if(typeof d!="string"||!ye(d,f)||typeof p!="string"||a&&(!o.some(m=>ye(m,f))||ue(f).currentBranch!==p))throw new Error(`Native SDK Supervisor worktree unavailable in this checkout: ${f}; transfer or repair the Child and integration worktrees before restoring the Run`)}}async function Qf(e,t){if(!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(t))throw new Error(`Invalid Native change name: ${t}`);let r=await ie(e.projectRoot,Ca.relative(e.projectRoot,e.archiveDir),{label:"Native SDK Archive directory",expected:"directory"});if(!r.exists)return null;let n=(await rE.readdir(r.target,{withFileTypes:!0})).filter(i=>i.isDirectory()&&!i.isSymbolicLink()&&/^\d{4}-\d{2}-\d{2}-/u.test(i.name)&&i.name.slice(11)===t).map(i=>i.name);if(n.length>1)throw new Error(`Native SDK Archive ${t} is ambiguous`);return n.length===1?Ca.join(r.target,n[0],"comet-state.yaml"):null}async function _a(e){let{text:t}=await ek({root:Ca.dirname(e),ref:Ca.basename(e),maxBytes:Buffer.byteLength(Hc)+1});return ms(t)}async function UW(e,t){let r=await rE.readFile(e,"utf8");if(!ms(r))return!1;let n=fa(r,"Native state file");return Ih(n[po],t)!==null}function B5(e,t,r,n){return Hc+(0,QW.stringify)({...M(e),...r===void 0?{}:{archive_receipt:r},...n?{application_checkpoint:n}:{}})+(t?`${po}: ${JSON.stringify(t)}
|
|
469
|
+
`:"")}function Ks(e,t={},r=!1){let n=Le(e),i=MW(e,"native",t.store??ht({singleWriter:!0,rootDir:Ca.join(n,"sdk-runs","native")}));function o(){if(Le(e)!==n)throw new Error("Native SDK workspace identity changed; recreate the store in the current workspace")}function a(f,d){return fa(d,"Native portable state")}async function s(f){return(await Qe(e,Ca.relative(e,f),Number.MAX_SAFE_INTEGER,{label:"Native portable state"})).bytes.toString("utf8")}async function c(f,d,p=t.readOnly){let m=await Te(e);if(!m)return null;let h=await we(e,m.native.artifact_root,{...t,readOnly:p,change:f}),g=Pt(h,f),v=g,w;try{w=await s(v)}catch(G){if(G.code!=="ENOENT")throw G;let Z=await Qf(h,f);if(!Z)return null;v=Z,w=await s(v)}if(!ms(w))return null;let y=fa(w,"Native state file"),R=Ih(y[po],f,{preserveSourceRevision:!0});if(!R)return null;if(D(y.application_checkpoint??null)!==D(t.identity??null))throw new Error("Native portable checkpoint requires its original fixed Application package");let N=M(y),b=R.input;if(!$5(M(R.state),N)||b?.name!==f||b.artifactRootRef!==h.artifactRootRef||R.workflow.id!=="comet-native"||v!==g&&!N.archived)throw new Error(`Native portable Run checkpoint for ${f} does not match its state`);if(!t.identity){let[{nativeSdkApplicationForRun:G},{upgradeNativeRun:Z}]=await Promise.all([Promise.resolve().then(()=>(Ff(),TW)),Promise.resolve().then(()=>(Hv(),OW))]);if(t.rootRunId===f&&R.lineage.length>0)throw new Error("Native Child Run must be restored through its original parent");let Ae=G(null);Z(R,Ae.workflow,Ae.transitionHandler)}!t.allowBranchRebind&&R.status!=="cancelled"&&!(N.archived&&R.status==="completed")&&hf(e,{isolation:N.workspace.isolation,changeBranch:N.workspace.change_branch,targetBranch:N.workspace.target_branch}),D5(R,N,e);let E=R.revision,I={...R,revision:E};if(d&&D(d)!==D({...I,revision:1}))throw new Error(`Native SDK Run ${f} differs from the interrupted checkpoint import; preserve the local records and restore matching Run history before continuing`);if(p)return I;if((E>1||d)&&!i.restoreCheckpoint)throw new Error(`Native RuntimeStore cannot restore checkpoint revision ${E}; use a store with restoreCheckpoint support or restore the original Run history`);let W=t.identity?.id??"native",F=N.archived&&R.status==="completed"?await Fe(e,"native",f,{readOnly:!0}):null;return(F?.application!==W||F.runId!==f)&&await Ro(e,{schema:pi,workflow:"native",change:f,format:"sdk",application:W,runId:f}),E===1&&!d?await i.compareAndSwap(f,null,I):await i.restoreCheckpoint(f,d?1:null,I),i.read(f)}async function l(f,d){let p=M(f.state),m=f.input;if(p.name!==f.runId||m?.name!==f.runId||typeof m.artifactRootRef!="string")throw new Error(`Native SDK Run ${f.runId} does not match its portable state`);let h=await Te(e);if(h&&h.native.artifact_root!==m.artifactRootRef)throw new Error("Native artifact root changed after Run creation");if(!d||!j5(f))return f;let g=f,v=p,w=await we(e,m.artifactRootRef,{change:f.runId}),y=Pt(w,f.runId);try{await rE.access(Ca.dirname(y))}catch(I){if(I.code!=="ENOENT")throw I;if(!v.archived)return g;let W=await Qf(w,f.runId);if(!W)throw new Error(`Native SDK Archive ${f.runId} is ambiguous`,{cause:I});y=W}let R=null;try{R=await s(y)}catch(I){if(I.code!=="ENOENT")throw I}let N=R&&g.actions.some(I=>I.stepId==="archive.finalize")?a(y,R).archive_receipt:void 0,b=JA(zA(g)),E=B5(v,b,N,t.identity);return R!==E&&await qe(y,E,{containedRoot:w.nativeRoot}),g}async function u(f,d=!1){let p;if(r)try{p=(await Ya(i,f)).record}catch(h){if(h.code!=="RUN_NOT_FOUND")throw h;p=null}else p=await i.read(f);let m=p?.revision===1&&p.actions.some(h=>h.status!=="pending")?p:void 0;if(!p||m){let h=await c(f,m,!0);if(!h)return p;if(!p||h.revision>p.revision){if(t.readOnly)throw new tE(e,f,!!m,t.identity);o(),await Cn(e),p=await c(f,m,!1)}}return p?l(p,d&&!t.readOnly):null}return{queryScope:i.queryScope,read:u,readProjection:f=>Ks(e,{...t,store:i,readOnly:!0},!0).read(f),async compareAndSwap(f,d,p){if(t.readOnly)throw new Error("Native SDK diagnostic store is read-only");o();let m=M(p.state);for(let N of p.actions){if(N.status!=="running"||!["verify.verifier","supervisor.child.verifier"].includes(N.stepId)||!zi(p,N))continue;let E=N.input.activation?.builderSessionId??m.builder_handoff?.builder_execution_ref;if(!E||N.claim?.sessionId!==E)continue;let I=await i.read(f),W=I?.actions.find(F=>F.id===N.id);if(I?.revision===d&&(W?.status!=="running"||!eE(W.claim,N.claim)))throw new A("VERIFIER_SESSION_NOT_INDEPENDENT","Native Verifier requires an independent session; use a different sessionId from the Builder.")}let h=m.workspace;try{hf(e,{isolation:h.isolation,changeBranch:h.change_branch,targetBranch:h.target_branch})}catch(N){let b=await i.read(f),E=p.actions.some(W=>W.status==="running"&&!b?.actions.some(F=>F.id===W.id&&F.status==="running"&&F.attempt===W.attempt&&eE(F.claim,W.claim))),I=b?.actions.some(W=>["running","unknown"].includes(W.status)&&p.actions.some(F=>F.id===W.id&&F.attempt===W.attempt&&eE(F.claim,W.claim)));if(E||p.status!=="cancelled"&&!I)throw N}let g=()=>i.compareAndSwap(f,d,p),v=[...p.actions].reverse().find(N=>N.stepId==="archive.execute"&&N.status==="failed"),y=(v?await i.read(f):null)?.actions.some(N=>N.id===v?.id&&N.status==="unknown"),R=p.status==="cancelled"?await HW({projectRoot:e,store:i,runId:f,expectedRevision:d,next:p}):y?await HB({projectRoot:e,store:i,runId:f,expectedRevision:d,next:p,actionId:v.id,state:m}):await g();return R&&(await l(p,!0),p.status==="cancelled"&&await Uv({projectRoot:e,run:p}),p.status==="completed"&&await Jv({projectRoot:e,run:p})),R}}}async function q5(e){let t=Wl(),r=Ks(e.paths.projectRoot);return wr({store:{async read(o){let a=await r.read(o);if(a&&!await Fe(e.paths.projectRoot,"native",o))throw new A("RUN_OWNER_MISSING",`SDK Run ${o} 缺少归属记录`);return a},async compareAndSwap(o,a,s){if(a===null){if(o!==e.name)throw new Error("Native SDK Run ID and change name differ");await Ro(e.paths.projectRoot,{schema:pi,workflow:"native",change:e.name,format:"sdk",application:"native",runId:o},{canonical:!0})}return r.compareAndSwap(o,a,s)}},workflows:[t.workflow],transitionHandlers:[t.transitionHandler],validators:t.validators,stateValidators:t.stateValidators,commandValidators:t.commandValidators,validateRecovery:t.validateRecovery,executors:t.executors}).start({runId:e.name,workflow:{id:t.workflow.id,version:t.workflow.version},input:{name:e.name,...e.task===void 0?{}:{task:e.task},artifactRootRef:e.paths.artifactRootRef},initialState:e.initialState})}async function JW(e,t){let r=W5.join(Mt(e,t),"comet-state.yaml");if(!await _a(r))return null;let n=await Jt(r),i=Gc({name:t,language:n.language,workspace:n.workspace,createdAt:n.created_at,nextAction:"prepare-shape-confirmation"});return JSON.stringify(n)!==JSON.stringify(i)?null:i}async function zW(e,t){let r=await JW(e,t);return r?q5({paths:e,name:t,initialState:r}):null}async function GW(e,t,r){if(r.lineage.length>0)throw new Error("Native Child Run must be restored through its original parent");let n=YW(),i=Ea(r,n.workflow,n.transitionHandler);return await wr({...n,workflows:[n.workflow],transitionHandlers:[n.transitionHandler],store:{read:async()=>i,compareAndSwap:async()=>!1}}).inspect(t),Ro(e,{schema:pi,workflow:"native",change:t,format:"sdk",application:"native",runId:t},{canonical:!0})}async function oE(e,t){let r=await Ao(e.projectRoot,"native",t);return r||$e(e,async()=>{let n=await Ao(e.projectRoot,"native",t);if(n)return n;let i=Uf.relative(e.projectRoot,Pt(e,t));if(!(await ie(e.projectRoot,i,{label:"Native legacy change state",expected:"file"})).exists){let c=await Qf(e,t);if(!c)return null;let l=Uf.relative(e.projectRoot,c),u=await ie(e.projectRoot,l,{label:"Native archived change state",expected:"file"});if(!u.exists||!await _a(u.target))return null;if(await nE(e.projectRoot,t))return await(await iE(e.projectRoot,t)).runtime.inspect(t),Fe(e.projectRoot,"native",t);let f=await Ks(e.projectRoot,{rootRunId:t}).read(t);if(f){let d=await Fe(e.projectRoot,"native",t);return d||GW(e.projectRoot,t,f)}throw new Error(`Native archived change ${t} has a managed state file but lost its Run checkpoint`)}if(await nE(e.projectRoot,t))return await(await iE(e.projectRoot,t)).runtime.inspect(t),Fe(e.projectRoot,"native",t);let s=await Ks(e.projectRoot,{rootRunId:t}).read(t);if(s){let c=await Fe(e.projectRoot,"native",t);return c||GW(e.projectRoot,t,s)}if(await zW(e,t)){let c=await Fe(e.projectRoot,"native",t);if(!c)throw new Error(`Recovered Native change ${t} has no Run ownership`);return c}return await L5(e,t),Ig(e.projectRoot,{schema:pi,workflow:"native",change:t,format:"compat"})})}async function L5(e,t){let r=Pt(e,t);if(await _a(r)&&!await UW(r,t))throw new Error(`Native change ${t} has a portable state file but lost its local Run history; inspect it with comet native doctor ${t} before restoring`)}async function nE(e,t){let r=await Te(e);if(!r)return null;let n=await we(e,r.native.artifact_root,{readOnly:!0}),i=Pt(n,t);try{await KW.access(i)}catch(a){if(a.code!=="ENOENT")throw a;let s=await Qf(n,t);if(!s)return null;i=s}return fa(await KW.readFile(i,"utf8"),"Native application checkpoint").application_checkpoint??null}var V5=to("nativeBuiltinDefinition",()=>Wl());function YW(){return V5()}async function iE(e,t,r={}){let n=r.owner??await Fe(e,"native",t,r),i=n?.application==="native"?null:await nE(e,t),o=n?.application??i?.id??"native";if(o==="native"){let c=Ks(e,{...r,rootRunId:t}),l=await c.read(t),u=YW();if(l){let f=Ea(l,u.workflow,u.transitionHandler);f!==l&&(await wr({...u,workflows:[u.workflow],transitionHandlers:[u.transitionHandler],store:{read:async()=>f,compareAndSwap:async()=>!1}}).inspect(t),l=f)}return{runtime:wr({...u,executors:r.readOnly?[]:u.executors,store:{...c,async read(f){if(l&&f===t){let p=l;return l=null,Promise.resolve(p)}let d=await c.read(f);return d&&Ea(d,u.workflow,u.transitionHandler)}},workflows:[u.workflow],transitionHandlers:[u.transitionHandler]}),executors:u.executors,application:null}}let a=i?.packageRoot?Uf.join(i.packageRoot,"application.json"):await TN(e,o,t),s=await Wg({file:a,projectRoot:e,runId:t,...i?{expectedIdentity:i}:{},readOnly:r.readOnly});if(s.identity.id!==o||s.identity.base!=="native")throw new Error("Native change owner does not match its fixed Application");return{runtime:wr({...s.implementation,...r.readOnly?{executors:[]}:{},store:s.store}),executors:s.implementation.executors??[],application:s}}async function Gs(e,t,r={}){let n=await Fe(e,"native",t,r);if(!n)throw new Error(`Native change ${t} is not owned by an SDK Run`);let{runtime:i,application:o}=await iE(e,t,{...r,owner:n}),a=await i.inspect(n.runId);if(a.workflow.id!=="comet-native"||!a.input||typeof a.input!="object"||Array.isArray(a.input)||a.input.name!==t||typeof a.input.artifactRootRef!="string")throw new Error(`Native SDK Run ${t} does not match its change ownership`);let s=M(a.state);if(s.name!==t)throw new Error(`Native SDK Run ${t} has a different state name`);return{run:a,state:s,artifactRootRef:a.input.artifactRootRef,application:o}}async function M5(e,t,r={}){let n=Uf.resolve(e);return await Fe(n,"native",t,r)?{projectRoot:n,...await Gs(n,t,r)}:null}async function XW(e,t,r={}){let n=Uf.resolve(e),i=await Ao(n,"native",t,r);if(!i&&!r.readOnly){let o=await Te(n);if(o){let a=await we(n,o.native.artifact_root,{change:t});i=await oE(a,t)}}return i?n:(await M5(n,t,r))?.projectRoot??n}it();import uq from"node:path";var F5=dr(Ur(),1);function ZW(e,t){return t.actions.filter(r=>["pending","running","unknown"].includes(r.status)).flatMap(r=>e.manifest.bindings.filter(n=>n.workflowId===t.workflow.id&&n.stepId===r.stepId).map(n=>{let i=e.skills.get(n.skillId);return{actionId:r.id,attempt:r.attempt,inputHash:r.inputHash,binding:n,skill:{id:i.id,root:i.root,contentHash:i.contentHash,adapter:i.adapter,files:i.files}}}))}or();it();bo();He();import Z5 from"node:path";Ja();Jc();function zv(e,t){return[...e,...t&&!e.includes("--project-root")?["--project-root",t]:[],...e.includes("--json")?[]:["--json"]]}function Kv(e){if(e.continuation.disposition!=="blocked")return;let{state:t,continuation:r,projectRoot:n}=e,i=zv(["comet","native","doctor",t.name],n),o=e.reason??(t.blockers.map(({reason:a})=>String(a)).join("; ")||`Native ${t.phase} requires inspection of the original execution before continuing.`);return{schema:"comet.native.recovery.v1",code:t.phase==="archive"?"archive-blocked":"runtime-recovery-required",reason:o,affectedPaths:[],owner:null,diagnosticArgs:i,recoveryArgs:r.commandArgs?zv(r.commandArgs,n):null,preconditions:r.requiredInputs.length?r.requiredInputs.map(a=>`Resolve the recorded condition: ${a}`):["Inspect the original Action and its retained evidence before retrying."],preserved:{candidateId:t.builder_handoff?.candidate_id??null,shapeConfirmationHash:t.shape_confirmation_hash??null}}}ai();Bd();Td();function Nr(e,t,r){return e.language==="zh-CN"?r:t}function H5(e,t,r){let n=i=>({required:!1,message:null,suggestedReply:null,agentInstruction:i});if(e.phase==="shape"&&e.status==="await-user"&&e.loop.next_action==="confirm-shape")return t?{required:!0,message:Nr(e,"Shape is ready. Confirm the complete plan and choose A) Multi-session coordination (recommended), or B) Single-session progression in one reply.","Shape 已整理完成。请确认完整方案,并在同一次回复中选择 A)多会话协作(推荐),或 B)单会话推进。"),suggestedReply:Nr(e,"Confirm the plan and use A","确认方案,按 A 开始"),agentInstruction:Nr(e,"First present the target, scope, key decisions, acceptance criteria, non-goals, child responsibilities and dependencies, and both coordination choices. Execute the matching confirm-shape alternative only when the user explicitly accepts this complete Shape and chooses its mode. Choosing a mode alone, additions, or corrections are not full confirmation; retain that choice and ask only for the missing decision. Do not run --confirmed before full confirmation.","先展示目标、范围、关键决定、验收标准、非目标、各 Child 的职责与依赖,以及两种推进方式。只有用户明确同意当前完整 Shape 并选择推进方式后,才执行对应的 confirm-shape 选项。仅选择推进方式、补充或修改要求都不算完整确认;保留已选方式,只补问缺少的决定。完整确认前不要运行 --confirmed。")}:e.language==="zh-CN"?{required:!0,message:"Shape 已整理完成。请确认目标、范围、关键决定、验收标准和非目标是否准确;明确确认后才会进入 Build。",suggestedReply:"确认进入 Build",agentInstruction:"先用自然语言简要展示目标、范围、关键决定、验收标准和非目标,再转述 message 并等待用户明确确认。只有用户明确同意当前完整 Shape 时,才执行 commandAlternatives 中的 confirm-shape;补充或修改要求不算确认。不要展示机器状态或提前运行 --confirmed。"}:{required:!0,message:"Shape is ready. Confirm that the target, scope, key decisions, acceptance criteria, and non-goals are accurate; Build starts only after explicit confirmation.",suggestedReply:"Confirm and enter Build",agentInstruction:"First present a concise natural-language summary of the target, scope, key decisions, acceptance criteria, and non-goals. Then relay message and wait for explicit user confirmation. Run confirm-shape from commandAlternatives only when the user explicitly accepts the complete current Shape; additions or corrections are not confirmation. Do not expose machine state or run --confirmed early."};if(t&&e.phase==="shape"&&e.status==="active")return n(Nr(e,"Complete the Shape documents and child plan, resolve blocking questions, then execute prepare-shape-confirmation. Its persisted response combines complete Shape confirmation and coordination choice in one user decision. If the user already chose only a mode, include that --coordination-mode when preparing and ask only for complete Shape confirmation afterward.","完成 Shape 文档和 Child 计划,解决阻塞问题后执行 prepare-shape-confirmation。持久化后的响应会让用户一次确认完整 Shape 并选择推进方式。如果用户已经仅选择了推进方式,准备时附上对应的 --coordination-mode,随后只确认完整 Shape。"));if(e.phase==="verify"&&e.status==="active"&&e.loop.stage==="verify-ready"&&e.loop.next_action!=="await-verifier-result")return n(Nr(e,"The current candidate and completed checks are preserved. Continue with dispatch-verifier without asking the user to recover files, processes, or workflow state. If a brief status update is necessary, say only that verification is being retried and the code is unchanged.","当前候选和已经完成的检查都已保留。直接继续 dispatch-verifier,不要让用户恢复文件、进程或工作流状态。如果确实需要简短同步进度,只说明正在重新尝试验收且代码没有变化。"));if(e.phase==="verify"&&e.status==="active"&&e.loop.next_action==="await-verifier-result")return n(`${Nr(e,"Keep the same dispatched Verifier while it is active. A wait-tool timeout is not an execution timeout: check task progress and continue waiting; do not cancel, interrupt, or spawn a replacement just because a wait returned without a result. Request progress without telling the Verifier to stop inspecting. Only after confirmed task failure, a platform-reported execution timeout, loss, or termination without a usable result, immediately submit verifier-execution-error. Preserve completed evidence and explain the failure and changed recovery approach before retrying. Submit verifier-unavailable only when the current platform truly has no usable subagent capability. Forward the actual report, including risks and incomplete checks; never turn an uninspected candidate into pass. Do not ask the user to recover files or processes, and do not expose attempt or requestCheckRounds.","已派发的验收任务仍在运行时,继续使用同一个 Verifier。等待工具超时不等于执行超时:检查任务进度并继续等待,不得仅因一次等待没有结果就取消、中断或重新派发。询问进度时不要要求停止核查。仅在确认任务失败、Agent 平台报告执行超时、任务丢失或结束后没有可用结果时,立即提交 verifier-execution-error;保留已完成证据,重试前说明失败原因及恢复方式的变化。只有当前平台确实没有可用的 subagent 能力时才提交 verifier-unavailable。忠实传递原始报告,包括风险和未完成检查;没有核查当前候选不能判定通过。不要让用户恢复文件或进程,也不要向用户展示 attempt、requestCheckRounds 等机器状态。")}`);if(e.status==="blocked"&&e.blockers.some(({resolution_action:i})=>i==="retry-verifier"))return e.loop.retry_epoch>=3?e.language==="zh-CN"?{required:!0,message:"自动重试验收已连续多轮未能取得结果,验证环境很可能不可用。请人工检查验证环境(subagent 配额、平台任务队列、网络),或使用 doctor --repair 评估该 change 状态。",suggestedReply:"人工检查验证环境",agentInstruction:"只向用户转述 message,等待用户完成人工检查后再继续。不要自动重试验收。"}:{required:!0,message:"Automatic verification retries have failed across multiple rounds; the verification environment is likely unavailable. Inspect the environment manually (subagent quota, platform task queue, network), or use doctor --repair to assess the change state.",suggestedReply:"Inspect the verification environment",agentInstruction:"Relay message to the user and wait for a manual environment check before continuing. Do not retry verification automatically."}:e.language==="zh-CN"?{required:!0,message:"由于独立验收任务连续几次没有正常返回结果,本次验收已暂停。你的代码和已经完成的检查都已安全保留。回复“继续”即可重新尝试,不需要处理文件或进程。",suggestedReply:"继续",agentInstruction:"只向用户转述 message 和 suggestedReply,并等待用户回复。不要展示内部轮次、计数、路径或恢复步骤。"}:{required:!0,message:"Verification paused because the independent verification task repeatedly ended without a result. Your code and completed checks are safely preserved. Reply “Continue” to retry; you do not need to manage files or processes.",suggestedReply:"Continue",agentInstruction:"Relay only message and suggestedReply to the user, then wait for that reply. Do not expose internal attempts, counters, paths, or recovery steps."};if(e.phase==="verify"&&e.status==="await-user"&&e.verification?.assurance==="semantic-verification-unavailable")return e.language==="zh-CN"?{required:!0,message:"独立验收当前不可用,但你的代码和已经完成的检查都已安全保留。你可以直接重新尝试独立验收,也可以明确接受只有自动检查的结果。",suggestedReply:"重新尝试独立验收",agentInstruction:"只向用户转述 message 和 suggestedReply,并等待用户选择。用户要求重试时执行 commandAlternatives 中的 retry-verifier;只有用户明确接受降级结果时才执行 confirm-verifier-unavailable。不要把“继续”视为接受降级结果,也不要要求用户处理文件、进程、服务或回调。"}:{required:!0,message:"Independent verification is currently unavailable, but your code and completed checks are safely preserved. You can retry independent verification directly or explicitly accept the automatic-check-only result.",suggestedReply:"Retry independent verification",agentInstruction:"Relay only message and suggestedReply, then wait for the user choice. If the user asks to retry, run retry-verifier from commandAlternatives; run confirm-verifier-unavailable only when the user explicitly accepts the degraded result. Do not treat “Continue” as accepting the degraded result, and do not ask the user to manage files, processes, services, or callbacks."};if(e.phase==="verify"&&e.status==="await-user"&&e.loop.next_action==="resolve-verifier-blocker")return e.language==="zh-CN"?{required:!0,message:"验证暂时无法下结论,因为缺少只有你能提供的信息,例如外部系统的真实行为或某个业务决定。你的代码和已经完成的检查都已安全保留。补充所需信息后可继续验证,也可以选择修改实现或调整需求。",suggestedReply:null,agentInstruction:"向用户转述 message,请用户补充缺失的信息,或在继续验证(resolve-verifier-blocker)、修改实现、调整需求之间明确选择,再执行 commandAlternatives 中对应的完整命令。不要把“继续”当作默认选择,也不要展示内部轮次、计数、路径或恢复步骤。"}:{required:!0,message:"Verification cannot reach a verdict yet because information only you can provide is missing, such as the real behavior of an external system or a business decision. Your code and completed checks are safely preserved. Supply the missing information to resume verification, or choose to revise the implementation or the requirements.",suggestedReply:null,agentInstruction:"Relay message and ask the user to supply the missing information or explicitly choose between resuming verification (resolve-verifier-blocker), revising the implementation, and revising the requirements; run the matching commandAlternative afterwards. Do not treat “Continue” as a default choice, and do not expose internal rounds, counters, paths, or recovery steps."};if(e.phase==="verify"&&e.status==="await-user"&&e.loop.next_action==="await-user"){let o=(e.loop.stop_reason??(e.loop.no_progress_count>=3?"stalled":"budget"))==="stalled",a=o?"验证已连续三轮失败且未通过的验收场景一直没有减少,本次修改已暂停,以避免在同一个问题上反复循环。你的代码和已经完成的检查都已安全保留。可以让 Builder 换一种修复思路继续,也可以回到需求阶段调整验收项。":"本次修改的验证失败次数已用完配置的预算,因此暂停等待你的决定,而不是自动重试。你的代码和已经完成的检查都已安全保留。可以让 Builder 换一种修复思路继续,也可以回到需求阶段调整验收项。注意:预算不会重置,选择继续修复后,下一次验收失败会再次暂停。",s=o?"Verification has failed three times in a row without the unresolved scenarios shrinking, so this change is paused to avoid looping on the same problem. Your code and completed checks are safely preserved. You can have the Builder try a different repair approach, or go back and adjust the requirements.":"Verification for this change has used its configured failure budget, so it is paused for your decision instead of retrying automatically. Your code and completed checks are safely preserved. You can have the Builder continue with a different repair approach, or go back and adjust the requirements.";return e.language==="zh-CN"?{required:!0,message:a,suggestedReply:"继续修复",agentInstruction:"向用户转述 message 和 suggestedReply,等待用户在“继续修复实现”(revise-implementation)与“调整需求”(revise-requirements)之间明确选择,再执行 commandAlternatives 中对应的完整命令。选择继续修复时,要求 Builder 更换修复思路。不要替用户选择,也不要展示内部轮次、计数、路径或恢复步骤。"}:{required:!0,message:s,suggestedReply:"Continue repairing",agentInstruction:"Relay message and suggestedReply, then wait for the user to explicitly choose between continuing the implementation (revise-implementation) and adjusting the requirements (revise-requirements); run the matching commandAlternative afterwards. When continuing, ask the Builder to change its repair approach. Do not choose for the user, and do not expose internal rounds, counters, paths, or recovery steps."}}if(e.phase==="verify"&&e.status==="await-user"&&e.verification_result==="pass"&&e.loop.next_action==="confirm-skill-coordinated-pass")return{required:!0,message:Nr(e,"The reported verification passed, but this platform cannot confirm an independent Verifier execution. Review the result and choose whether to accept it for Archive, revise the implementation, or revise the requirements."+(e.workspace.isolation!=="current"&&e.workspace.finish===null?" If accepting, also choose: keep the workspace, merge locally, push the branch, or push and create a PR. You may accept the result and defer the finish choice.":""),"当前验收报告已通过,但当前平台无法确认验收是否独立执行。请检查结果,并选择接受结果进入归档、继续修改实现,或调整需求。"+(e.workspace.isolation!=="current"&&e.workspace.finish===null?" 接受时可一起选择:保留工作区、本地合并、推送分支,或推送并创建 PR;也可以先接受结果,稍后再选择收尾方式。":"")),suggestedReply:Nr(e,"Accept the result","接受结果"),agentInstruction:Nr(e,"Summarize the result and verification evidence, relay the message, and wait for an explicit user decision. Only then execute the matching commandAlternative. Do not accept the result on the user’s behalf.","简要说明交付结果和验收证据,转述 message,并等待用户明确选择后再执行对应的 commandAlternative。不要替用户接受结果。")};if(e.phase==="build"&&e.status==="active"){let i=r?.children.some(({status:c})=>c==="blocked")??!1,o=r?.children.some(({status:c})=>c==="needs-reverify")??!1,a=r?.children.some(({status:c})=>c==="ready"||c==="active")??!1,s=r?.children.some(({status:c,builderFailureCount:l})=>c==="blocked"&&(l??0)>=qh)??!1;return i&&!o&&!a&&!s?e.language==="zh-CN"?{required:!0,message:"Supervisor 子任务暂时无法启动,已暂停自动重试以避免流程循环。请先根据子任务 blocker 修复工作区、分支或依赖;修复完成后重新运行最新的 next 继续流程。代码和已有证据已保留。",suggestedReply:"修复 blocker 后继续",agentInstruction:"向用户说明子任务 blocker 和需要先完成的外部修复;不要反复执行 next,也不要创建替代任务。用户确认工作区或依赖已修复后,再重新读取 status 并执行最新 continuation。"}:{required:!0,message:"Supervisor child dispatch is paused because every remaining child is blocked. Automatic retries are stopped to avoid a loop. Resolve the recorded child blocker (workspace, branch, or dependency) first, then read the latest status and continue; code and completed evidence are preserved.",suggestedReply:"Resolve the blocker and continue",agentInstruction:"Explain the child blocker and the required external repair to the user. Do not repeatedly run next or spawn replacement tasks. After the user confirms the workspace or dependency is fixed, read status again and execute the latest continuation."}:n(Nr(e,"Implement the complete confirmed brief and Spec scope, then review every acceptance ID with its implementation and evidence before handoff. Fill acceptance_review from this audit; derive remaining work from it. Do not submit a partial candidate just to obtain verification feedback. Run focused checks; a separate pre-review is optional. If review is useful, retain the same Reviewer for focused repair follow-ups. Submit the completed candidate for one complete independent verification and release completed helper tasks.","完成已确认的 brief 和 Spec 全部范围,交接前逐项核对所有验收 ID 的实现和证据,填写 acceptance_review,并由这份自查生成剩余工作。不得提交未完成的候选来试探验收反馈。开发期运行相关检查,额外预审为可选项;确需审查时,保留同一个 Reviewer 复核修复及受影响范围。全部完成后提交一次完整独立验收,及时释放已完成的辅助任务。"))}return n(Nr(e,"Follow the continuation action. Unless required is true, continue without asking the user to handle internal workflow state, and do not present machine fields as a user-facing explanation.","按 continuation 执行下一步。除非 required 为 true,否则继续推进,不要让用户处理内部工作流状态,也不要把机器字段作为面向用户的说明。"))}function Q5(e){let t=e.workspace.change_branch??"<change-branch>",r=e.workspace.target_branch??"<target-branch>";return e.language==="zh-CN"?{required:!0,message:`当前 change 位于 ${t},目标分支为 ${r}。请选择一次工作区收尾方式:A) 保留工作区;B) 本地合并;C) 推送分支;D) 推送并创建 PR;E) 暂不归档。选择 A-D 后 Runtime 会完成预检,检查通过后按所选方式归档;选择 E 将保留当前 change 等待稍后继续。`,suggestedReply:"回复 A、B、C、D 或 E",agentInstruction:"向用户展示五种收尾方式及实际影响,等待用户选择。选择 A-D 时执行对应 commandAlternatives 的完整命令,Runtime 会在归档前检查状态和证据;选择 E 时停止,不运行 Archive 命令。按用户的明确选择执行 finish。"}:{required:!0,message:`This change is on ${t} and targets ${r}. Choose one workspace finish: A) keep the workspace; B) merge locally; C) push the branch; D) push and create a PR; or E) defer Archive. For A-D, Runtime will run preflight and archive with the selected finish when the checks pass; E keeps the current change for later.`,suggestedReply:"Reply A, B, C, D, or E",agentInstruction:"Show all five finish choices and their actual effects, then wait. For A-D, execute the matching complete commandAlternative; Runtime checks state and evidence before archiving. For E, stop without running an Archive command. Use the finish explicitly selected by the user."}}function U5(e){return[...[{finish:"keep",name:"keep-workspace",description:["保留当前分支和目录;完成归档提交,不合并、不推送、不创建 PR。","Keep the current branch and directory; create the archive commit without merging, pushing, or creating a PR."]},{finish:"merge",name:"merge-locally",description:["完成归档提交,并把 change 分支本地合并到目标分支;不推送、不创建 PR。","Create the archive commit and merge the change branch locally into the target branch without pushing or creating a PR."]},{finish:"push",name:"push-branch",description:["完成归档提交并推送 change 分支;不合并到目标分支、不创建 PR。","Create the archive commit and push the change branch without merging into the target branch or creating a PR."]},{finish:"pull-request",name:"push-pull-request",description:["完成归档提交、推送 change 分支,并以目标分支为基础创建 PR。","Create the archive commit, push the change branch, and create a PR against the target branch."]}].map(({finish:n,name:i,description:o})=>({name:i,stateVersion:e.state_version,expectedAction:"archive",commandArgs:["comet","native","archive",e.name,"--confirmed","--finish",n,"--expected-state-version",String(e.state_version)],requiredInputs:[],inputOptions:[],description:Nr(e,o[1],o[0])})),{name:"defer-archive",stateVersion:e.state_version,expectedAction:"archive-preview",commandArgs:null,requiredInputs:[],inputOptions:[],description:Nr(e,"Keep the current change and workspace without archiving; stop and resume later.","保留当前 change 和工作区,不执行归档;停止本次流程,稍后再继续。")}]}function rq(e){return["comet","native","next",e.change,"--summary","<summary>",e.flag,"--expected-state-version",String(e.stateVersion),"--expected-action",e.action]}function Ys(e,t){return{name:e,flag:t,valueKind:"text",required:!0,template:null}}function J5(e,t){return{name:e,flag:t,valueKind:"confirmation",required:!0,template:null}}function eq(e,t,r){return{name:e,flag:t,valueKind:"choice",required:!0,template:null,choices:[...r]}}function z5(e){return e?.coordinationChoiceRequired===!0||e?.schema==="comet.native.children.v2"&&e.children.length>=2}function K5(e){return["comet","native","next",e.change,"--summary","<summary>","--expected-state-version",String(e.stateVersion),"--expected-action","prepare-shape-confirmation"]}function Jn(e){return{name:e.name,stateVersion:e.stateVersion,expectedAction:e.expectedAction,commandArgs:rq({change:e.change,stateVersion:e.stateVersion,action:e.expectedAction,flag:e.flag}),requiredInputs:["summary",e.confirmationInput],inputOptions:[Ys("summary","--summary"),J5(e.name,e.flag)]}}function tq(e,t){return t.some(n=>/^verification\.md is (?:missing|stale|invalid)$/u.test(n))?[{name:"repair-verification-report",stateVersion:e.state_version,expectedAction:"archive-preview",commandArgs:["comet","native","doctor",e.name,"--repair"],requiredInputs:[],inputOptions:[],description:Nr(e,"Rebuild the Runtime-managed verification report, then rerun the Archive dry-run.","重建由 Runtime 管理的 verification.md,然后重新运行 Archive 预检。")}]:[]}function G5(e){return/^verification\.md is (?:missing|stale|invalid)$/u.test(e)}function Gv(e){return[Jn({name:"revise-implementation",change:e.change,stateVersion:e.stateVersion,expectedAction:"revise-implementation",flag:"--revise-implementation",confirmationInput:"user-decision"}),Jn({name:"revise-requirements",change:e.change,stateVersion:e.stateVersion,expectedAction:"revise-requirements",flag:"--revise-requirements",confirmationInput:"user-decision"})]}function Y5(e){let t={"final-result":"Choose when the Verifier has a result for every current scope ID.","verifier-execution-error":"Choose when a dispatched Verifier failed, was lost, or ended without a result.","verifier-unavailable":"Choose only when the platform has no usable independent Verifier capability."};return e.flatMap(r=>Array.isArray(r.template)?r.template.map(n=>{let i=n.response?.kind??n.kind;return{...r,name:i,required:!1,exclusiveGroup:"runner-input",description:t[i],template:n}}):[r])}function ql(e,t,r={}){let n=X5(e,t,e.verifier_action?{...r,verifierExecutionRef:GA(e.verifier_action)??r.verifierExecutionRef}:r),i=Kv({state:e,continuation:n,reason:r.archiveBlockers?.join("; ")||void 0});return i?{...n,recovery:i}:n}function X5(e,t,r={}){let n=z5(t)&&e.coordination_mode===void 0,i=H5(e,n,t),o={schema:"comet.native.continuation.v2",skill:"comet-native",change:e.name,phase:e.phase,status:e.status,stateVersion:e.state_version,...e.status==="active"?{contextRequest:Yc(e)}:{},mode:"execute",inputOptions:[],requiresUserDecision:i.required,userCommunication:i},a=s=>({kind:s,candidateId:e.builder_handoff?.candidate_id??null,iteration:e.loop.iteration,attempt:e.loop.attempt});if(e.status==="done")return{...o,disposition:"done",mode:"done",action:"none",commandArgs:null,requiredInputs:[],runnerAction:a("none")};if(e.status==="await-user")return e.phase==="shape"&&e.loop.next_action==="confirm-shape"?{...o,disposition:"await-user",mode:"ask",action:"confirm-shape",commandArgs:null,requiredInputs:["summary","shared-understanding-confirmation",...n?["coordination-choice"]:[]],inputOptions:[Ys("summary","--summary")],commandAlternatives:n?Od.map(s=>{let c=Jn({name:`confirm-shape-${s}`,change:e.name,stateVersion:e.state_version,expectedAction:"confirm-shape",flag:"--confirmed",confirmationInput:"shared-understanding-confirmation"});return{...c,commandArgs:[...c.commandArgs,"--coordination-mode",s],requiredInputs:[...c.requiredInputs,"coordination-choice"],inputOptions:[...c.inputOptions,eq("coordination-mode","--coordination-mode",[s])]}}):[Jn({name:"confirm-shape",change:e.name,stateVersion:e.state_version,expectedAction:"confirm-shape",flag:"--confirmed",confirmationInput:"shared-understanding-confirmation"})],runnerAction:a("none")}:e.phase==="verify"&&e.verification_result==="pass"&&e.loop.next_action==="confirm-skill-coordinated-pass"?{...o,disposition:"await-user",mode:"ask",action:"confirm-skill-coordinated-pass",commandArgs:null,requiredInputs:["summary","user-decision"],inputOptions:[Ys("summary","--summary")],commandAlternatives:[...e.workspace.isolation!=="current"&&e.workspace.finish===null?["keep","merge","push","pull-request"].map(s=>{let c=Jn({name:`accept-result-${s}`,change:e.name,stateVersion:e.state_version,expectedAction:"accept-result",flag:"--accept-result",confirmationInput:"user-decision"});return{...c,commandArgs:[...c.commandArgs,"--finish",s]}}):[],Jn({name:"accept-result",change:e.name,stateVersion:e.state_version,expectedAction:"accept-result",flag:"--accept-result",confirmationInput:"user-decision"}),Jn({name:"retry-verifier",change:e.name,stateVersion:e.state_version,expectedAction:"retry-verifier",flag:"--retry-verifier",confirmationInput:"user-decision"}),...Gv({change:e.name,stateVersion:e.state_version})],runnerAction:a("none")}:e.phase==="verify"&&e.verification?.assurance==="semantic-verification-unavailable"&&e.loop.next_action==="confirm-verifier-unavailable"?{...o,disposition:"await-user",mode:"ask",action:"confirm-verifier-unavailable",commandArgs:null,requiredInputs:["summary","user-decision"],inputOptions:[Ys("summary","--summary")],commandAlternatives:[Jn({name:"retry-verifier",change:e.name,stateVersion:e.state_version,expectedAction:"retry-verifier",flag:"--retry-verifier",confirmationInput:"user-decision"}),Jn({name:"confirm-verifier-unavailable",change:e.name,stateVersion:e.state_version,expectedAction:"confirm-verifier-unavailable",flag:"--confirmed",confirmationInput:"user-decision"})],runnerAction:a("none")}:e.phase==="verify"&&e.loop.next_action==="resolve-verifier-blocker"?{...o,disposition:"await-user",mode:"ask",action:"resolve-verifier-blocker",commandArgs:null,requiredInputs:["summary","user-decision"],inputOptions:[Ys("summary","--summary")],commandAlternatives:[Jn({name:"resolve-verifier-blocker",change:e.name,stateVersion:e.state_version,expectedAction:"resolve-verifier-blocker",flag:"--resolve-verifier-blocker",confirmationInput:"user-resolution"}),...Gv({change:e.name,stateVersion:e.state_version})],runnerAction:a("none")}:e.phase==="verify"&&e.loop.next_action==="await-user"?{...o,disposition:"await-user",mode:"ask",action:"resolve-loop-stop",commandArgs:null,requiredInputs:["summary","user-decision"],inputOptions:[Ys("summary","--summary")],commandAlternatives:Gv({change:e.name,stateVersion:e.state_version}),runnerAction:a("none")}:{...o,disposition:"await-user",mode:"ask",action:"none",commandArgs:null,commandAlternatives:Gv({change:e.name,stateVersion:e.state_version}),userCommunication:{...o.userCommunication,required:!0,message:e.blockers.length>0?e.blockers.map(({reason:s})=>s).join("; "):o.userCommunication.message,suggestedReply:e.blockers.length>0?e.blockers[0]?.resolution_action??null:o.userCommunication.suggestedReply},requiredInputs:["resolve-blocker"],runnerAction:a("none")};if(e.status==="blocked"){let s=e.blockers.some(({resolution_action:c})=>c==="retry-verifier");return{...o,disposition:"blocked",mode:"reconcile",action:s?"retry-verifier":"none",commandArgs:s?rq({change:e.name,stateVersion:e.state_version,action:"retry-verifier",flag:"--retry-verifier"}):null,requiredInputs:s?["summary"]:["repair-runtime"],inputOptions:s?[{name:"summary",flag:"--summary",valueKind:"text",required:!0,template:null}]:[],runnerAction:a(s?"retry-verifier":"none")}}if(e.phase==="shape")return{...o,disposition:"continue",action:"prepare-shape-confirmation",commandArgs:K5({change:e.name,stateVersion:e.state_version}),requiredInputs:["summary"],inputOptions:[{name:"summary",flag:"--summary",valueKind:"text",required:!0,template:null}],runnerAction:a("none")};if(e.phase==="build"){if(t){if(!t.confirmed)return{...o,disposition:"blocked",mode:"reconcile",action:"repair",commandArgs:null,requiredInputs:[],inputOptions:[],runnerAction:a("none"),userCommunication:{...i,agentInstruction:"restore children.yaml and retry next; preserve the original Child tasks and approved scope. Do not dispatch or accept results while the scope is unavailable."}};if(t.allDone)return{...o,disposition:"continue",action:"builder-handoff",commandArgs:["comet","native","next",e.name,"--runner-input","<temporary-json-file>"],...e.loop.stage==="repairing"&&e.verification_result==="fail"?{commandAlternatives:[Jn({name:"revise-requirements",change:e.name,stateVersion:e.state_version,expectedAction:"revise-requirements",flag:"--revise-requirements",confirmationInput:"user-decision"})]}:{},requiredInputs:["builder-handoff-json-file"],inputOptions:[{name:"runner-input",flag:"--runner-input",valueKind:"json-file",required:!0,template:{kind:"builder-handoff",summary:"<summary>",addressed_acceptance_ids:e.acceptance.map(({id:m})=>m),acceptance_review:e.acceptance.map(({id:m})=>({id:m,status:Si(Uu),evidence:[],note:"<implementation and evidence summary>"})),checks:[{name:"<check-name>",result:Si(Hu),note:null}],known_limits:[]}}],runnerAction:a("builder-handoff")};let s=t.children.find(({status:m})=>m==="verified");if(s)return{...o,disposition:"continue",action:"advance-children",commandArgs:["comet","native","next",e.name,"--runner-input","<temporary-json-file>"],requiredInputs:["supervisor-integration-result"],inputOptions:[{name:"runner-input",flag:"--runner-input",valueKind:"json-file",required:!0,template:{kind:"supervisor-integrate",child:s.name,integrationCommit:"<actual-integration-commit>",checks:[{name:"<check-name>",status:"<passed|failed|incomplete>",reason:"<actual-result>"}]}}],runnerAction:a("none")};let c=t.children.some(({status:m})=>m==="blocked"||m==="needs-reverify"),l=t.children.some(({status:m})=>m==="needs-reverify"),u=t.children.some(({status:m})=>m==="ready"||m==="active"),f=t.supervisorStateVersion===void 0?null:t.children.find(m=>m.status==="blocked"&&(m.builderFailureCount??0)>=qh)??null,d=f===null?null:{name:"runner-input",flag:"--runner-input",valueKind:"json-file",required:!0,template:{kind:"supervisor-retry-builder",child:f.name,stateVersion:t.supervisorStateVersion},description:Nr(e,"Explicitly authorize one fresh Builder attempt after the Builder failure budget was exhausted.","Builder 失败预算已耗尽;明确授权后才能重新开始一次 Builder 尝试。")},p=c&&!l&&!u&&d===null;return{...o,disposition:p?"blocked":"continue",mode:p?"reconcile":"execute",action:"advance-children",commandArgs:p?null:d!==null?["comet","native","next",e.name,"--runner-input","<temporary-json-file>"]:["comet","native","next",e.name,"--summary","<summary>",...e.coordination_mode==="single-session"?["--max-parallel","1"]:[]],requiredInputs:p?[]:d!==null?["supervisor-builder-retry-json-file"]:["ready-children"],inputOptions:p?[]:d!==null?[d]:[Ys("summary","--summary")],runnerAction:a("none")}}return{...o,disposition:"continue",action:e.loop.stage==="repairing"?"repair":"builder-handoff",commandArgs:["comet","native","next",e.name,"--runner-input","<temporary-json-file>"],requiredInputs:["builder-handoff-json-file"],inputOptions:[{name:"runner-input",flag:"--runner-input",valueKind:"json-file",required:!0,template:{kind:"builder-handoff",summary:"<summary>",addressed_acceptance_ids:e.acceptance.map(({id:s})=>s),acceptance_review:e.acceptance.map(({id:s})=>{let c=e.builder_handoff?.acceptance_review?.find(l=>l.id===s);return c?{...c,evidence:[...c.evidence],...e.loop.previous_unresolved_ids.includes(s)?{status:"implemented-no-evidence",evidence:[],note:"<current repair and evidence summary>"}:{}}:{id:s,status:Si(Uu),evidence:[],note:"<implementation and evidence summary>"}}),checks:[{name:"<check-name>",result:Si(Hu),note:null}],known_limits:[]}}],runnerAction:a("builder-handoff")}}if(e.phase==="verify"){let s=e.loop.next_action==="await-verifier-result",c=!!e.children_contract_ref;return{...o,userCommunication:!s&&c?{...o.userCommunication,agentInstruction:`${o.userCommunication.agentInstruction} ${Nr(e,"Run necessary integration checks with platform tools and reuse applicable Child reports. Parent acceptance must cover every confirmed criterion.","使用平台工具执行必要的集成检查,复用适用的子任务报告。父级验收仍须覆盖全部已确认条目。")}`}:o.userCommunication,disposition:"continue",mode:s?"wait":"execute",action:s?"await-verifier":"dispatch-verifier",commandArgs:["comet","native","next",e.name,"--runner-input","<temporary-json-file>"],requiredInputs:[s?"verifier-response-or-error-json-file":"verifier-dispatch-json-file"],inputOptions:Y5([{name:"runner-input",flag:"--runner-input",valueKind:"json-file",required:!0,template:s?[{kind:"verifier-response",candidateId:e.builder_handoff?.candidate_id??"<candidate-id>",verifierExecutionRef:r.verifierExecutionRef??"<from verifierDispatch>",response:{kind:"final-result",result:{iteration:e.loop.iteration,attempt:e.loop.attempt,verdict:Si(Ua),acceptance:[{id:"<acceptance-id>",result:Si(Qu),reason:"<reason>"}],risks:[],summary:"<summary>"}}},{kind:"verifier-execution-error",summary:"<summary>",stateVersion:e.state_version,iteration:e.loop.iteration,attempt:e.loop.attempt,verifierExecutionRef:r.verifierExecutionRef??"<from verifierDispatch>"},{kind:"verifier-unavailable",summary:"<why no independent semantic execution is available>",stateVersion:e.state_version,iteration:e.loop.iteration,attempt:e.loop.attempt,verifierExecutionRef:r.verifierExecutionRef??"<from verifierDispatch>"}]:{kind:"dispatch-verifier"}}]),runnerAction:a(s?"await-verifier":"dispatch-verifier")}}if(e.phase==="archive"&&e.status==="active"&&e.loop.stage==="archive-ready"&&!e.archived){let s=r.archiveMode??"archive-ready",l=e.workspace.isolation!=="current"&&e.workspace.finish===null;if(s==="blocked")return{...o,disposition:"blocked",mode:"reconcile",action:"archive",commandArgs:null,requiredInputs:["archive-blocker-resolution"],inputOptions:[],runnerAction:a("none")};if(s==="preview"){if(r.archiveBlockers&&r.archiveBlockers.length>0){let u=tq(e,r.archiveBlockers)[0];return u&&r.archiveBlockers.every(f=>G5(f))?{...o,disposition:"continue",action:"repair",commandArgs:u.commandArgs,requiredInputs:[],inputOptions:[],runnerAction:a("none")}:{...o,disposition:"blocked",mode:"reconcile",action:"archive",commandArgs:null,requiredInputs:["archive-blocker-resolution"],inputOptions:[],commandAlternatives:tq(e,r.archiveBlockers),runnerAction:a("none")}}return{...o,disposition:"continue",action:"archive",commandArgs:["comet","native","archive",e.name,"--confirmed"],requiredInputs:[],runnerAction:a("none")}}return l?{...o,disposition:"await-user",mode:"ask",action:"archive",commandArgs:null,requiredInputs:["workspace-finish"],inputOptions:[eq("finish","--finish",["keep","merge","push","pull-request"])],commandAlternatives:[...U5(e)],userCommunication:Q5(e),runnerAction:a("none")}:{...o,disposition:"continue",action:"archive",commandArgs:["comet","native","archive",e.name,"--dry-run"],requiredInputs:[],commandAlternatives:[Jn({name:"revise-requirements",change:e.name,stateVersion:e.state_version,expectedAction:"revise-requirements",flag:"--revise-requirements",confirmationInput:"user-decision"})],runnerAction:a("none")}}return{...o,disposition:"continue",action:"archive",commandArgs:["comet","native","archive",e.name,"--confirmed"],requiredInputs:[],runnerAction:a("none")}}Ft();import nq from"node:path";function iq(e){let t=e.replace(/\s+/gu," ").trim();return t.length<=240?t:`${t.slice(0,237)}...`}function Ll(e,t){let r=e.acceptance.reduce((n,i)=>({...n,[i.result]:n[i.result]+1}),{total:e.acceptance.length,passed:0,failed:0,blocked:0,pending:0});return{schema:"comet.native.state-summary.v1",name:e.name,phase:e.phase,status:e.status,state_version:e.state_version,...e.coordination_mode===void 0?{}:{coordination_mode:e.coordination_mode},loop:e.loop,acceptance:r,unresolved_acceptance_ids:e.acceptance.filter(({result:n})=>n==="failed"||n==="blocked").map(({id:n})=>n),verification_result:e.verification_result,blockers:e.blockers.slice(0,8).map(n=>({owner:n.owner,reason:iq(n.reason.text),acceptance_ids:n.acceptance_ids,resolution_action:n.resolution_action})),workspace:{isolation:e.workspace.isolation,change_branch:e.workspace.change_branch,target_branch:e.workspace.target_branch,finish:e.workspace.finish},learning:{failureResolved:e.verification_result==="pass"&&e.history.some(n=>n.outcome==="fail"&&n.goal_cycle===e.loop.goal_cycle),...e.verification?{summary:iq(e.verification.summary.text)}:{},artifactRefs:t?["brief.md",...e.verification_report?[e.verification_report]:[],...e.spec_changes.map(n=>n.source).filter(n=>n!==null)].slice(0,16).map(n=>nq.relative(t.projectRoot,nq.join(t.changesDir,e.name,n)).replaceAll("\\","/")):[]},archived:e.archived}}Co();Cr();bo();YR();Oi();function oq(e,t,r=ue(e.projectRoot)){let n=null;return t.workspace.change_branch!==null&&(r.isGitWorktree?r.currentBranch!==t.workspace.change_branch&&(n=`Expected branch ${t.workspace.change_branch}, current branch is ${r.currentBranch??"(detached)"}.`):n="The Native change requires a registered Git worktree."),n===null&&t.workspace.isolation==="worktree"&&!r.isSecondaryWorktree&&(n="The Native change requires its linked worktree."),{projectRoot:Z5.resolve(e.projectRoot),isolation:t.workspace.isolation,bindingState:n===null?"aligned":"mismatch",changeBranch:t.workspace.change_branch,targetBranch:t.workspace.target_branch,finish:t.workspace.finish,message:n}}Eo();it();ze();Ja();Se();Jc();vv();Eo();yv();Mf();ES();VS();QN();Bd();function sq(e){if(["failed","cancelled","completed"].includes(e.status))return[];let t=e.actions.filter(n=>n.status==="pending"),r=t.findIndex(n=>n.stepId==="supervisor.child.archive");return r>0&&t.unshift(...t.splice(r,1)),t}function eX(e,t){if(!(e.waits.some(r=>r.status==="pending")||e.evidenceWaits?.some(r=>r.status==="pending")||e.actions.some(r=>r.status==="unknown")||t.phase==="archive"&&e.actions.some(r=>r.status==="running")))return sq(e)[0]}function Xs(e,t){return[...e,...e.includes("--project-root")?[]:["--project-root",t],...e.includes("--json")?[]:["--json"]]}function aE(e,t){return{...e,cwd:t,commandArgs:e.commandArgs?Xs(e.commandArgs,t):null,...e.commandAlternatives?{commandAlternatives:e.commandAlternatives.map(r=>({...r,commandArgs:r.commandArgs?Xs(r.commandArgs,t):null}))}:{}}}function tX(e,t){return Xs(["comet","runtime","dispatch","--application",e,"--request","<request-json-file>"],t)}function rX(e,t,r){let n=r.input?.activation,i=(Array.isArray(n?.acceptance)?n.acceptance:t.acceptance).map(({id:o})=>({id:o,result:"<passed|failed|blocked>",reason:"<observed-evidence>"}));return["build.builder","supervisor.parent.builder"].includes(r.stepId)?{summary:"<actual-implementation-summary>",addressedAcceptanceIds:t.acceptance.map(({id:o})=>o),checks:[{name:"<check-name>",result:"<passed|failed|not-run>",note:"<actual-result>"}],knownLimits:["<actual-limit-or-remove-entry>"],requireIndependentReview:!1,...r.stepId==="supervisor.parent.builder"?{candidateCommit:"<current-integration-HEAD>"}:{}}:r.stepId==="verify.verifier"?{checks:(t.builder_handoff?.checks??[]).map(o=>({name:o.name.text,result:o.result,note:o.note?.text??null})),candidateId:t.builder_handoff?.candidate_id??null,verifierExecutionRef:r.claim?.sessionId??"<actual-session-id>",response:{kind:"final-result",result:{iteration:t.loop.iteration,attempt:t.loop.attempt,verdict:"<pass|fail|blocked>",acceptance:i,risks:["<observed-risk-or-remove-entry>"],summary:"<verification-summary>",...typeof e.input.task=="string"?{requestReview:{result:Si(Rm),reason:"<compare the original request, Spec and implementation; cite authorization for changed scope>"}}:{}}}}:r.stepId==="supervisor.child.builder"?{candidateCommit:"<current-child-HEAD>",checks:[],summary:"<implementation-summary>",requireIndependentReview:!1}:r.stepId==="supervisor.child.verifier"?{candidateCommit:n?.candidateCommit??null,verdict:"<pass|fail|blocked>",evidence:{summary:"<verification-summary>",checks:n?.checks??[],acceptance:i}}:r.stepId==="supervisor.child.integration-repair"?{summary:"<repair-summary>",integrationCommit:"<new-integration-HEAD>",checks:[{name:"<check-name>",result:"<passed|failed|not-run>",note:"<actual-result>"}]}:"<actual-action-output>"}function nX(e,t,r){return!t.claim||!["running","unknown"].includes(t.status)?null:{operation:"record-outcome",runId:e.runId,outcome:{actionId:t.id,attempt:t.attempt,inputHash:t.inputHash,claimToken:t.claim.token,outcomeId:"<outcome-id>",status:t.type==="handoff"?"succeeded":"<succeeded|failed>",output:rX(e,r,t)}}}function iX(e,t,r,n){let i=nX(e,t,r);return i?{operation:"record-outcome",receipt:Buffer.from(JSON.stringify({runId:e.runId,actionId:t.id,attempt:t.attempt,inputHash:t.inputHash,claimToken:t.claim.token})).toString("base64url"),result:{status:i.outcome.status,output:n===void 0?i.outcome.output:n}}:null}function oX(e,t){if(t.type!=="handoff"||!t.claim||t.status==="running"&&!t.reason)return{};let r={runId:e.runId,expectedRevision:e.revision,actionId:t.id,attempt:t.attempt};return t.status==="running"?{markUnknownRequest:{operation:"mark-unknown",...r,reason:"<why-the-original-outcome-cannot-be-obtained>"}}:t.status!=="unknown"||t.outcome||t.rejectedOutcomes?.some(n=>n.outcome.attempt===t.attempt)?{}:{retryRequest:{operation:"retry",...r,reconciliation:{resolution:"not-executed",evidence:null}},requiredInputs:["reconciliation.evidence: authoritative evidence that the original host task never executed"]}}function aX(e,t){let r=ql(e);if(!t)return r;let n=e.language==="zh-CN";return{...r,requiredInputs:["summary","shared-understanding-confirmation","coordination-mode"],commandAlternatives:Od.map(i=>({name:i,stateVersion:e.state_version,expectedAction:"confirm-shape",commandArgs:["comet","native","next",e.name,"--summary","<summary>","--confirmed","--coordination-mode",i,"--expected-state-version",String(e.state_version),"--expected-action","confirm-shape"],requiredInputs:["summary","shared-understanding-confirmation","coordination-mode"],inputOptions:[{name:"summary",flag:"--summary",valueKind:"text",required:!0,template:null},{name:"shared-understanding-confirmation",flag:"--confirmed",valueKind:"confirmation",required:!0,template:null},{name:"coordination-mode",flag:"--coordination-mode",valueKind:"choice",required:!0,template:i,choices:[...Od]}]})),userCommunication:{required:!0,message:n?"请确认完整 Shape,并选择推进方式:多会话协作(推荐)或单会话推进。":"Confirm the complete Shape and choose multi-session coordination (recommended) or single-session progression.",suggestedReply:n?"确认 Shape,选择多会话协作":"Confirm Shape with multi-session coordination",agentInstruction:n?"先简要展示目标、范围、关键决定、验收标准、非目标及 Child 计划,再转述 message。只有用户明确确认当前完整 Shape 并选定推进方式后,才执行对应的 commandAlternatives;补充或修改要求不算确认。":"Summarize the target, scope, key decisions, acceptance criteria, non-goals, and child plan before relaying message. Execute the matching commandAlternative only after the user explicitly confirms the complete current Shape and chooses a coordination mode; additions or corrections are not confirmation."}}}function sX(e,t,r){let n=ql(t),i=HN(e,t).filter(({wait:o})=>o.proposalHash===r);return t.loop.next_action==="resolve-verifier-blocker"&&!i.some(({action:o})=>o==="resolve-verifier-blocker")?{...n,action:"none",disposition:"blocked",mode:"reconcile",requiresUserDecision:!1,commandArgs:["comet","native","doctor",t.name,"--repair"],commandAlternatives:void 0,requiredInputs:[],inputOptions:[],userCommunication:{required:!1,message:null,suggestedReply:null,agentInstruction:t.language==="zh-CN"?"更新原 Run 的恢复选项,然后重新读取 continuation。保留候选和检查;只有用户明确决定后才重新验收或修复实现,不需要重新确认需求。":"Update the original Run recovery choices, then read its continuation again. Preserve the candidate and checks; retry verification or repair only after an explicit user decision. Do not reset the requirements."}}:{...n,commandAlternatives:[...i.map(({action:o,wait:a})=>Nn(t,o,a.proposalHash)),Nn(t,"revise-requirements")]}}function Nn(e,t,r){return{name:t,stateVersion:e.state_version,expectedAction:t,commandArgs:["comet","native","next",e.name,`--${t}`,"--summary","<summary>",...r===void 0?[]:["--proposal-hash",r],"--expected-state-version",String(e.state_version),"--expected-action",t],requiredInputs:["summary","user-decision"],inputOptions:[{name:"summary",flag:"--summary",valueKind:"text",required:!0,template:null}]}}async function cq(e){let r=await cX(e),n=[...e.run.actions].reverse().find(c=>["failed","unknown","running"].includes(c.status)),i=n?.outcome?.output,o=!!(i?.reason==="candidate-drift"&&e.state.phase==="verify"&&n&&e.run.actions.indexOf(n)>e.run.actions.map(c=>["build.builder","supervisor.parent.builder"].includes(c.stepId)&&c.status==="succeeded").lastIndexOf(!0)),a=typeof i?.message=="string"?i.message:(Array.isArray(i?.blockers)?i.blockers.filter(c=>typeof c=="string").join("; "):"")||n?.reason||e.run.reason||r.continuation.userCommunication.message||void 0,s=Kv({state:e.state,continuation:o?{...r.continuation,disposition:"blocked",commandArgs:r.continuation.commandAlternatives?.find(c=>c.name==="revise-implementation")?.commandArgs??r.continuation.commandArgs}:r.continuation,projectRoot:e.projectRoot,reason:a});if(s&&n&&(s.owner={actionId:n.id,attempt:n.attempt,executorId:n.claim?.executorId??null,sessionId:n.claim?.sessionId??null},n.stepId==="archive.prepare"?s.code="archive-preflight-blocked":["unknown","running"].includes(n.status)&&(s.code="execution-unresolved"),o&&(s.code="candidate-drift")),o&&!e.state.loop.stop_reason){let c=e.state.language==="zh-CN",l=r.continuation.commandAlternatives?.find(u=>u.name==="revise-implementation");if(l){let u={...l,requiredInputs:["summary"]};r.continuation={...r.continuation,disposition:"continue",mode:"execute",action:"repair",requiresUserDecision:!1,commandArgs:u.commandArgs,requiredInputs:u.requiredInputs,inputOptions:u.inputOptions,commandAlternatives:r.continuation.commandAlternatives?.map(f=>f.name==="revise-implementation"?u:f),userCommunication:{required:!1,message:null,suggestedReply:null,agentInstruction:c?"先检查实际修改。若用户已有授权继续且改动仍在已确认需求范围内,执行 revise-implementation,保留现有工作和原检查,再建立后继候选并独立验收;不重建需求或重复原一次性检查。若需求或验收标准变化,走需求修订并重新确认;缺少继续授权或需要新增权限时先询问。不得自动接受新候选或沿用失效证据。":"Inspect the actual edits first. If the user has already authorized continued work and the edits remain within approved requirements, run revise-implementation, retain the existing work and original checks, and independently verify a successor candidate; do not recreate requirements or repeat original one-shot checks. If requirements or acceptance criteria changed, revise and reconfirm them; ask when continued work or additional permissions are not authorized. Do not automatically accept the successor or reuse invalid evidence."}}}}return s?{...r,continuation:{...r.continuation,recovery:s}}:r}function aq(e,t,r){let n=e.input,i=n?.activation??n,o=i?.worktree;return Yc({name:t.name,phase:e.ref?.includes("verifier")?"verify":"build",language:t.language,projectRoot:typeof o=="string"?o:r,sessionId:e.claim?.sessionId,task:[t.name,...i?.child?[i.child]:[],...(i?.acceptance??(i?.child?[]:t.acceptance)).map(({text:a})=>a)].join(`
|
|
470
|
+
`).slice(0,4e3)})}async function cX(e){let{run:t,state:r,projectRoot:n}=e,i=tX(e.applicationId??"native",n),o=(b,E)=>r.language==="zh-CN"?E:b,a=(b,E=null)=>({required:E!==null,message:E,suggestedReply:null,agentInstruction:b}),s={schema:"comet.native.continuation.v2",skill:"comet-native",change:r.name,phase:r.phase,status:r.status,stateVersion:r.state_version,...r.status==="active"?{contextRequest:Yc({name:r.name,phase:r.phase,language:r.language,projectRoot:n})}:{},disposition:"continue",mode:"execute",requiresUserDecision:!1,action:"none",commandArgs:null,requiredInputs:[],inputOptions:[],runnerAction:{kind:"none",candidateId:r.builder_handoff?.candidate_id??null,iteration:r.loop.iteration,attempt:r.loop.attempt},userCommunication:a(o("Continue from the current SDK Run.","按当前 SDK Run 继续。"))},c=await _D({projectRoot:n,run:t,state:r,base:s,cancellationObservation:e.cancellationObservation});if(c)return{...c,continuation:aE(c.continuation,n)};if(t.status==="failed"){let b=ZB(t.reason),E=QB(t),I=UB(t);return{continuation:aE({...s,disposition:"blocked",mode:"reconcile",commandArgs:E||I?["comet","native","archive",r.name]:b?["comet","native","doctor",r.name,"--repair"]:["comet","native","doctor",r.name],requiredInputs:[],userCommunication:a(I?o("Archive finalization stopped before writing because the confirmed candidate changed. Restore the confirmed implementation and materials, then run archive to continue the existing Spec transaction.","归档收尾在写入前发现候选漂移并停止。恢复已确认的实现和材料后,执行 archive 继续原 Spec 事务。"):E?o("Archive preflight found blockers without changing the confirmed report. Resolve its blockers, then rerun archive to retry the read-only inspection. Existing receipts and approval remain bound to this candidate.","Archive 预检发现阻塞,未改写已确认报告。消除阻塞后重新执行 archive,只重试只读检查;原收据和审批仍绑定同一候选。"):o("The Run stopped. Inspect it with doctor and preserve the original failed receipts; do not claim pending work, retry an executed failure, or report that it never ran.","Run 已停止。请使用 doctor 核对并保留原失败收据;不能领取遗留待执行工作、重跑已执行失败的旧 Action,或声称它未执行。"))},n)}}let l=sq(t),u=eX(t,r),f=l.map(b=>{let E=b.type==="invoke_skill"?e.skillExecutors?.find(I=>I.supports(b)):void 0;return{id:b.id,stepId:b.stepId,type:b.type,ref:b.ref,attempt:b.attempt,inputHash:b.inputHash,mechanism:"runtime-dispatch",...typeof t.input.task=="string"?{originalRequest:{source:"run.input.task",text:t.input.task}}:{},commandArgs:b.type==="handoff"||b.type==="invoke_skill"?i:Xs(["comet","native","next",r.name],n),...b.type==="handoff"?{contextRequest:aq(b,r,n),...b.ref?.includes("verifier")?{sessionRequirements:{independent:zi(t,b),readOnly:!0,mustDifferFromSessionId:zi(t,b)?b.stepId==="verify.verifier"?r.builder_handoff?.builder_execution_ref??null:b.input?.activation?.builderSessionId??null:null,resumeCommandArgs:Xs(["comet","native","status",r.name],n),instruction:zi(t,b)?o("Launch a separate read-only session in this project. Pass this Action input and claimRequest to it, without adding Builder conclusions or turning design choices into expected behavior. That session must claim with its own stable session ID before verification and submit its own outcome; the Builder must not claim on its behalf.","在此项目启动独立只读会话,将本 Action 输入和 claimRequest 交给它,不附加 Builder 的自评或把设计取舍写成预期行为。由该会话在验收前使用自己的稳定会话标识领取,并提交自己的结果;Builder 不代领。"):o("Review the original request and current candidate using valid checks. Use this session or a separate reviewer according to the actual uncertainty and user requirements. Claim with the reviewing session identity and submit its actual conclusion.","依据原始请求、当前候选和有效检查完成验收。根据具体疑问和用户要求选择当前会话或独立审查。使用实际审查会话领取并提交真实结论。")}}:{},claimRequest:{operation:"claim",runId:t.runId,actionId:b.id,attempt:b.attempt,inputHash:b.inputHash,executorId:"native-host",sessionId:"<session-id>",claimToken:D({runId:t.runId,actionId:b.id,attempt:b.attempt,inputHash:b.inputHash})}}:{},...b.type==="invoke_skill"?{executeRequest:E?{operation:"execute",runId:t.runId,expectedRevision:t.revision,actionId:b.id,executorId:E.id}:null}:{},...b.type==="handoff"||b.type==="invoke_skill"?{input:b.input}:{}}}),d=t.waits.filter(b=>b.status==="pending"),p=(t.evidenceWaits??[]).filter(b=>b.status==="pending"),m=d.filter(b=>["build.resume","supervisor.child.resume","supervisor.parent.resume","supervisor.child.integration-resume"].includes(b.stepId)).map(b=>({waitId:b.id,stepId:b.stepId,proposalHash:b.proposalHash,commandArgs:Xs(Nn(r,"continue-builder",b.proposalHash).commandArgs,n)})),h=d.filter(b=>b.stepId.startsWith("native.extension.revise.")).map(b=>({waitId:b.id,proposalHash:b.proposalHash,proposal:b.proposal,commandArgs:Xs(Nn(r,"revise-requirements").commandArgs,n),message:o("The extension found changed requirements. Confirm whether to return to Shape after reconciling running or unknown work.","扩展发现需求变化。先核对 running/unknown 工作,再确认是否返回 Shape 修订需求。")})),g,v=d.find(b=>["verify.confirm","verify.retry","verify.stop"].includes(b.stepId)),w=t.actions.filter(b=>b.status==="running"||b.status==="unknown"),y=SW(t),R=NS(t),N=R!==void 0&&SS(t,r,R.proposalHash);if(t.status==="completed")g={...s,disposition:r.status==="done"?"done":"blocked",mode:r.status==="done"?"done":"reconcile",commandArgs:r.status==="done"?null:["comet","native","doctor",r.name],userCommunication:a(o(r.status==="done"?"SDK Archive has completed. Finish and verify any Git delivery already authorized by the user before reporting the task complete; Run completion alone does not prove commit, push, or PR delivery.":"The Run ended without completing the Native change. Inspect preserved results and follow Doctor before reporting completion.",r.status==="done"?"SDK 归档已完成。宣告任务完成前,继续执行并核对用户已经授权的 Git 交付;Run 完成不能证明提交、推送或 PR 已完成。":"Run 已结束,但 Native change 尚未完成。核对保留的结果并按 Doctor 恢复,不能宣告完成。"))};else if(y.length>0)g={...s,action:"retry-verifier",disposition:"await-user",mode:"ask",requiresUserDecision:!0,requiredInputs:["summary","user-decision"],commandAlternatives:y.flatMap(b=>[...b.choices.includes("retry")?[Nn(r,"retry-verifier",b.proposalHash)]:[],...b.choices.includes("repair")?[Nn(r,"revise-implementation",b.proposalHash)]:[]]),userCommunication:a(o("Preserve the failed execution receipt and independent Child progress. After an explicit decision, retry only the failed Child with its current candidate and checks, or return it to a new Builder. Never report an executed failure as not executed.","保留失败执行收据与其他 Child 的进度。明确决定后,仅为失败 Child 复用当前候选和检查派发新 Verifier,或交给新 Builder 修复。不能将已执行失败报告为未执行。"),o("A Child Verifier execution failed. Retry its independent review, or repair this Child first?","Child Verifier 执行失败。是否重新尝试独立验收,或先修复这个 Child?"))};else if(h.length>0||m.length>0){let b=h.length>0;g={...s,disposition:"await-user",mode:"ask",requiresUserDecision:!0,commandAlternatives:b?[Nn(r,"revise-requirements")]:m.map(E=>Nn(r,"continue-builder",E.proposalHash)).concat(N?[Nn(r,"revise-requirements",R.proposalHash)]:[]),requiredInputs:["summary","user-decision"],userCommunication:a(o("Preserve completed work, reconcile running or unknown Actions, and execute the matching option only after the user decides.","保留已完成工作,先核对 running/unknown Action,用户明确决定后执行对应选项。"),b?h[0].message:m.some(E=>E.stepId==="supervisor.child.integration-resume")?o("The integration repair failed. Continue from its preserved integration workspace?","集成修复执行失败。是否从保留的集成工作区继续修复?"):N?o("The Builder stopped before completing this work. Continue from its preserved workspace, or revise the requirements and confirm a new Shape?","Builder 尚未完成本轮工作。请选择从保留的工作区继续,或调整需求并重新确认 Shape。"):o("The Builder stopped before completing this work. Continue from its preserved workspace?","Builder 尚未完成本轮工作。是否从保留的工作区继续?"))}}else if(v?.stepId==="verify.stop")g=sX(t,r,v.proposalHash);else if(v){let b=v.stepId==="verify.retry",E=HN(t,r).filter(({wait:I})=>I.id===v.id);g={...s,disposition:"await-user",mode:"ask",requiresUserDecision:!0,action:b?"retry-verifier":"confirm-skill-coordinated-pass",requiredInputs:["summary","user-decision"],commandAlternatives:[...E.map(({action:I,wait:W})=>Nn(r,I,W.proposalHash)),...b?[]:[Nn(r,"revise-requirements")]],userCommunication:a(o("Summarize the result and evidence, then wait for an explicit decision before executing the matching option.","简要说明结果和证据,等待用户明确决定后执行对应选项。"),b?o("Verification stopped without a usable result. Retry the independent Verifier with the preserved candidate and checks?","验收未正常返回可用结果。是否保留当前候选和检查,重新尝试独立验收?"):o("Verification passed. Accept the result for Archive, revise the implementation, or revise the requirements?","验收已通过。请选择接受结果进入归档、修改实现,或调整需求。"))}}else if(r.phase==="shape"&&w.length===0){let b=d.find(E=>["shape.confirm","supervisor.shape.confirm"].includes(E.stepId));g=aX(r,b?.stepId==="supervisor.shape.confirm"),b&&(g={...g,commandAlternatives:[...g.commandAlternatives??[],Nn(r,"revise-requirements",b.proposalHash)],userCommunication:{...g.userCommunication,agentInstruction:g.userCommunication.agentInstruction+" "+o("When the user requests changed requirements, finish updating the Shape documents and execute revise-requirements to reject this proposal and prepare a new one. Then ask for explicit approval of the new complete Shape; revision never grants approval.","用户要求调整需求时,先补全 Shape 文档,再执行 revise-requirements 拒绝旧提案并准备新提案。随后请用户明确批准新的完整 Shape;修订本身不代表批准。")}})}else if(w.length===1&&w[0].stepId==="repair.implementation"&&w[0].ref==="native-revise-implementation"&&w[0].claim?.executorId==="comet-native-revise-implementation"&&["running","unknown"].includes(w[0].status))g={...s,disposition:"continue",mode:"execute",commandArgs:["comet","native","next",r.name],userCommunication:a(o("Recheck the original read-only implementation revision with its existing claim; this does not assume the original process stopped and does not execute Archive.","使用原领取信息重新核对只读实现修订;不假定原进程已停止,也不执行 Archive。"))};else if(w.length===1&&w[0].status==="unknown"&&w[0].stepId==="verify.revalidate"&&w[0].ref==="native-report-revalidate"&&w[0].claim?.executorId==="comet-native-report-revalidate")g={...s,disposition:"continue",mode:"execute",commandArgs:["comet","native","next",r.name],userCommunication:a(o(`Report revalidation stopped: ${w[0].reason??"unknown result"}. Run next to repeat only the read-only validation with the original claim. Changed checks require fresh verification; unresolved storage or permission errors remain blocked.`,`报告复核停止:${w[0].reason??"结果未知"}。执行 next,只重读校验并保留原领取记录;检查失效后重新验收,未解决的存储或权限错误仍保持阻塞。`))};else if(r.phase==="archive"&&w.length===1&&(w[0].status==="unknown"||w[0].status==="running"&&w[0].stepId==="archive.prepare"&&w[0].claim?.executorId==="comet-native-archive-preflight"&&w[0].rejectedOutcomes?.some(b=>b.outcome.attempt===w[0].attempt))&&gS.some(([b,E])=>w[0].stepId===b&&w[0].ref===E))g={...s,action:"archive",disposition:"blocked",mode:"reconcile",commandArgs:["comet","native","archive",r.name,"--recover"],requiredInputs:["original-archive-writer-stopped","archive-conflict-resolution"],userCommunication:a(o(`The original Archive step stopped: ${w[0].reason??"its outcome is unresolved"}. Confirm the original writer stopped and resolve the reported path or permission conflict, then run the recovery command. It reconciles the same transaction and Action; completed checks and applied Specs are retained.`,`原归档步骤已停止:${w[0].reason??"执行结果尚未核对"}。确认原写入进程已停止,处理报告中的路径或权限冲突后执行恢复命令。恢复会核对同一事务和 Action,保留已完成检查及已应用规格。`))};else if(w.some(b=>b.status==="unknown"))g={...s,disposition:"blocked",mode:"reconcile",commandArgs:null,requiredInputs:["original-execution-result"],userCommunication:a(o("Reconcile the original Action and execution before continuing. Submit its actual outcome if it executed. Only authoritative evidence that a host task never executed permits its retryRequest; an unknown result or a timeout is not that evidence.","先核对原 Action 和执行现场。已执行时提交原领取的真实结果;只有权威证据证明宿主任务确未执行,才可填写其 retryRequest。结果未知或等待超时不是未执行证据。"))};else if(d.length>0||p.length>0)g={...s,disposition:d.length>0?"await-user":"blocked",mode:d.length>0?"ask":"reconcile",requiresUserDecision:d.length>0,requiredInputs:[d.length>0?"user-decision":"runtime-evidence"],userCommunication:a(o("Review the pending SDK Wait and its complete proposal before submitting a decision or evidence with the original identity. Do not repeat Archive to skip it.","先核对待处理 SDK Wait 及其完整提案,再按原身份提交决定或证据。不能重复归档来跳过它。"),d.length>0?o("An application decision is required before continuing.","应用需要新的决定才能继续。"):null)};else if(u){let b=u,E=b.type==="handoff",I=b.type==="invoke_skill",W=r.phase==="archive"&&l.length===1&&b.type==="call_tool"&&gS.some(([G,Z])=>b.stepId===G&&b.ref===Z),F=f[0].executeRequest;g={...s,action:E?b.ref?.includes("verifier")?"dispatch-verifier":"builder-handoff":W?"archive":"none",disposition:I&&!F?"blocked":"continue",mode:I&&!F?"reconcile":"execute",commandArgs:E||I&&F?["comet","runtime","dispatch","--application",e.applicationId??"native","--request","<request-json-file>"]:I?null:["comet","native",W?"archive":"next",r.name],...E?{...b.stepId==="build.builder"&&_v(t)?{commandAlternatives:[Nn(r,"revise-requirements",_v(t))]}:{},requiredInputs:["request-json-file","session-id","claim-token"],inputOptions:[{name:"request-json-file",flag:"--request",valueKind:"json-file",required:!0,template:f[0].claimRequest}]}:{},...I?{requiredInputs:F?["request-json-file"]:["skill-executor"],inputOptions:F?[{name:"request-json-file",flag:"--request",valueKind:"json-file",required:!0,template:F}]:[]}:{},userCommunication:a(I?o("Execute the pending Skill with its fixed Application executor and skillWork contract. If no compatible executor is configured, resolve that host requirement; repeating native next cannot execute this Skill.","按 skillWork 契约使用固定 Application 的执行器运行待处理 Skill。缺少适配执行器时先补全宿主要求;重复 native next 不能执行此 Skill。"):E?o("Use the pending Action claimRequest with a real stable session ID and unique claim token. After the claim succeeds, the receiving Agent reads context[].text; execute contextRequest only when the response has no contextDelivery. Use the returned Action input; Verifiers need a separate read-only session. Submit the original Action outcome, then follow the returned Run.","在待执行 Action 的 claimRequest 中填入真实稳定的会话标识和唯一领取令牌。领取成功后,接收 Agent 先读取 context[].text;响应没有 contextDelivery 时才执行自己的 contextRequest,再按返回的 Action 输入开展工作;Verifier 必须使用独立只读会话。提交原 Action 的结果后按返回的 Run 继续。"):W?o("Execute Archive once and follow the returned state. If the platform returns a background handle, wait for that original task with its wait/output tool. After completion, parse its original stdout as one complete JSON document and keep stderr separate. Do not poll unrelated processes, parse task-status decorations as JSON, or start another Archive while this task is running.","只执行一次 Archive,并按返回状态继续。平台返回后台句柄时,使用对应的等待或输出工具跟踪原任务。完成后把原 stdout 作为一个完整 JSON 文档解析,stderr 另存;不要轮询无关进程、把任务状态提示当作 JSON,或在原任务运行时再启动 Archive。"):o("Execute the next Runtime-owned Action and follow its returned state. It revalidates current evidence before committing.","执行下一项 Runtime 自有 Action,并按返回状态继续;Runtime 会在提交前重新校验当前证据。"))}}else w.length>0?g={...s,mode:"wait",commandArgs:null,requiredInputs:["original-execution-result"],userCommunication:a(o("Continue or wait on the original claimed task. Do not create a second task because a wait timed out; submit its actual outcome with the original claim.","继续或等待原已领取任务。等待超时不能另建任务;用原领取信息提交真实结果。"))}:r.status==="done"?g={...s,disposition:"done",mode:"done"}:t.ready.length>0?g={...s,commandArgs:["comet","native","next",r.name]}:g={...s,disposition:"blocked",mode:"reconcile",requiredInputs:["runtime-evidence-or-decision"],userCommunication:a(o("Inspect the pending SDK Wait or evidence requirement before continuing; do not submit a compat Runner input.","先核对待处理的 SDK Wait 或证据要求;不要提交 compat Runner 输入。"))};return r.workspace.change_branch&&!r.archived&&!["completed","cancelled"].includes(t.status)&&ue(n).currentBranch!==r.workspace.change_branch&&(g={...g,disposition:"blocked",mode:"reconcile",action:"none",commandArgs:["comet","native","select",r.name,"--rebind"],commandAlternatives:void 0,requiredInputs:["confirm-current-branch-ownership","settle-original-executions"],userCommunication:a(`当前分支与需求绑定的 ${r.workspace.change_branch} 不一致。切回原分支继续;确认当前分支接管且原执行已结束后,执行 select --rebind,保留同一 Run 和已有工作。`)}),{continuation:aE(g,n),...w.length>0?{activeActions:w.map(b=>({id:b.id,stepId:b.stepId,status:b.status,attempt:b.attempt,inputHash:b.inputHash,input:b.input,type:b.type,ref:b.ref,claim:b.claim,...b.reason?{reason:b.reason}:{},...b.type==="handoff"?{contextRequest:aq(b,r,n)}:{},commandArgs:i,resultRequest:iX(t,b,r),...oX(t,b)}))}:{},...t.status!=="completed"&&f.length>0?{pendingAction:(()=>{let{input:b,...E}=f[0];return{...E,...b===void 0?{}:{inputRef:"pendingActions[0].input"}}})(),pendingActions:f}:{},...d.length>0?{pendingWaits:d.map(b=>({...b,...["verify.stop","verify.retry","verify.confirm"].includes(b.stepId)?{choices:Ls(r,b,t).map(({choice:E})=>E)}:{},commandArgs:i,decisionRequests:(["verify.stop","verify.retry","verify.confirm"].includes(b.stepId)?Ls(r,b,t).map(({choice:E})=>E):b.choices).map(E=>({operation:"resolve-wait",runId:t.runId,expectedRevision:t.revision,waitId:b.id,proposalHash:b.proposalHash,decisionId:"<decision-id>",choice:E,...b.stepId==="verify.stop"&&E==="retry"?{reason:"<summary>"}:{}}))}))}:{},...p.length>0?{pendingEvidenceWaits:p.map(b=>({...b,commandArgs:i,evidenceRequest:{operation:"record-evidence",runId:t.runId,expectedRevision:t.revision,evidenceId:b.id,kind:b.kind,ref:"<evidence-relative-path>",contentHash:"<actual-evidence-sha256>",submissionId:"<submission-id>"}}))}:{},...m.length>0?{pendingBuilderDecisions:m}:{},...y.length>0?{pendingVerifierDecisions:y.map(b=>({waitId:b.id,proposalHash:b.proposalHash,proposal:b.proposal}))}:{},...h.length>0?{pendingRequirementDecisions:h}:{}}}it();ze();Rl();lr();or();Se();vv();Eo();import lX from"node:path";async function lq(e,t,r={}){let n=await Fe(e,"native",t.runId,{readOnly:!0}),i=n&&n.application!=="native"?await ED(e,n.application,t.runId):await ht({singleWriter:!0,rootDir:lX.join(Le(e),"sdk-runs/native")}).readPartitionMetadata(t.runId),o=["active","closed"].includes(i),a=t.actions.filter(m=>m.status==="unknown"),s=t.actions.some(m=>m.stepId==="archive.finalize"&&m.status==="cancelled"&&!m.outcome);if(s)try{await XB({projectRoot:e,run:t,readOnly:!0}),s=!1}catch{}let c=[],l=[...t.actions].reverse().find(m=>m.stepId==="archive.prepare");l?.status==="failed"&&c.push({code:"native-archive-preflight-blocked",runId:t.runId,message:l.outcome?.output?.message??"Native Archive 预检未通过,请核对原 Action",nextCommand:"comet native status "+t.runId+" --json"});let u=t.status==="cancelled"?await So({projectRoot:e,run:t,ownerObservation:n}):null,f=n?.application==="native"&&i==="closed"&&u?.status==="cancelled",d=M(t.state),p=[...!f&&!d.archived&&d.workspace.change_branch&&ue(e).currentBranch!==d.workspace.change_branch?[{code:"native-workspace-branch-mismatch",runId:t.runId,message:"当前分支与原 Run 绑定不一致;切回原分支,或确认接管并核对原执行已结束。",nextCommand:`comet native select ${t.runId} --rebind --json`}]:[],...c,...u?.cleanupRequired?[{code:"sdk-cancellation-cleanup-pending",runId:t.runId,message:u.cleanup?.reason??"原 Run 的业务取消尚未完成工作区收尾",nextCommand:u.cleanup?.finishCommand??`comet native doctor ${t.runId} --repair --json`}]:u?.status==="cancelling"?[{code:"sdk-cancellation-business-pending",runId:t.runId,message:"原 Run 仍有未核对结果的业务任务,请检查原任务后再完成取消",nextCommand:`comet native status ${t.runId} --details --json`}]:[],...o?[]:[{code:i==="missing"?"storage-run-missing":"storage-transaction-pending",runId:t.runId,message:`Native 存储状态为 ${i},尚未完成核对或收尾`,nextCommand:`comet native doctor ${t.runId} --repair --json`}],...a.map(m=>({code:"native-execution-outcome-unresolved",runId:t.runId,actionId:m.id,message:"原执行结果尚未核对,不能重放执行",nextCommand:m.stepId==="archive.finalize"?`comet native archive ${t.runId} --recover --json`:`comet native status ${t.runId} --details --json`})),...s?[{code:"native-cancelled-archive-finalization-unresolved",runId:t.runId,message:"已取消的归档仍保留未核对的原收据,需要恢复历史事务收尾",nextCommand:`comet native archive ${t.runId} --recover --json`}]:[]];return{stateReadable:!0,executionReconciled:a.length===0,storageSettled:o,healthy:p.length===0,issues:p}}Co();Eo();var dq=12;function sE(e,t){if(t)return{items:e,omitted:0};let r=new Set(["pending","running","unknown"]),n=0,i=!1,o=[];for(let a=e.length-1;a>=0;a-=1){let s=e[a],c=s.status==="failed"&&!i;s.status==="failed"&&(i=!0),(r.has(s.status)||n++<dq||c)&&o.push(s)}return o.reverse(),{items:o,omitted:e.length-o.length}}var fq=(...e)=>Zp(()=>uX(...e));async function uX(e,{run:t,state:r,artifactRootRef:n,application:i}){let o=Ll(r),a=await So({projectRoot:e.projectRoot,run:t}),s=sE(t.actions,e.details),c=sE(t.waits,e.details),l=sE(t.evidenceWaits??[],e.details),u=t.actions.flatMap(d=>{let p=d.outcome?.output;return d.stepId!=="verify.report"||d.status!=="succeeded"||typeof p?.preservedReportRef!="string"||!/^native\/preserved-verification\/[a-f0-9]{64}\/[a-f0-9]{64}\.md$/u.test(p.preservedReportRef)||typeof p.preservedReportSha256!="string"?[]:[{ref:p.preservedReportRef,path:uq.join(Le(e.projectRoot),...p.preservedReportRef.split("/")),sha256:p.preservedReportSha256}]}),f=await PB(e.projectRoot,t);return{schema:"comet.native.sdk-status.v1",diagnostics:await lq(e.projectRoot,t,{}),runtimeFormat:"sdk",...i?{application:i.identity,skillWork:ZW(i,t)}:{},name:e.name,preservedReportsDirectory:{ref:Ms(t.runId),path:uq.join(Le(e.projectRoot),Ms(t.runId))},...u.length?{preservedReports:u}:{},...f?{warning:f}:{},language:r.language,phase:r.phase,status:a?.status??r.status,stateVersion:r.state_version,acceptance:o.acceptance,unresolvedAcceptanceIds:o.unresolved_acceptance_ids,verificationResult:r.verification_result,candidateId:r.builder_handoff?.candidate_id??null,blockers:o.blockers,workspace:oq({projectRoot:e.projectRoot},r),run:{id:t.runId,revision:t.revision,status:t.status,history:{settledLimit:dq,actions:{total:t.actions.length,omitted:s.omitted,truncated:s.omitted>0},waits:{total:t.waits.length,omitted:c.omitted,truncated:c.omitted>0},evidenceWaits:{total:(t.evidenceWaits??[]).length,omitted:l.omitted,truncated:l.omitted>0},...s.omitted+c.omitted+l.omitted>0?{detailsCommandArgs:["comet","native","status",e.name,"--details","--json"]}:{}},actions:s.items.map(({id:d,stepId:p,status:m,attempt:h,inputHash:g,reason:v,outcome:w})=>({id:d,stepId:p,status:m,attempt:h,inputHash:g,...v??w?.output?.message?{reason:v??(w?.output).message}:{}})),waits:c.items.map(({id:d,stepId:p,status:m,proposalHash:h,choices:g})=>({id:d,stepId:p,status:m,proposalHash:h,choices:g})),evidenceWaits:l.items.map(({id:d,stepId:p,kind:m,status:h})=>({id:d,stepId:p,kind:m,status:h}))},...await cq({run:t,state:r,projectRoot:e.projectRoot,applicationId:i?.identity.id,implementationRevisionAvailable:!i||i.implementation.workflows.some(d=>d.id==="comet-native"&&!!d.commands?.["revise-implementation"]),skillExecutors:i?.implementation.executors,cancellationObservation:a}),...e.details?{details:{state:r}}:{}}}Ft();it();import{randomUUID as jX}from"node:crypto";import{promises as $q}from"node:fs";import rw from"node:path";ze();lr();lt();Yn();or();import dX from"node:path";async function pq(e,t,r,n,i=[]){let o=await ie(e,t,{label:"旧业务材料",expected:"file"});if(!o.exists||await Nk(o.target))return;let a=await ie(r,n,{label:"当前业务材料",expected:"file"});if(a.exists)return;let s=(await Qe(e,t,Number.MAX_SAFE_INTEGER,{label:"旧业务材料"})).bytes;await $t(r,dX.posix.dirname(n),{label:"业务导入目录"});try{await Dt(a.target,s.toString("utf8"),{containedRoot:r,exclusive:!0}),i.push(n)}catch(c){if(c.code!=="EEXIST")throw c}}or();dt();Er();Hi();St();qR();Es();sf();Ft();Se();He();Pf();Nf();dt();Hi();Ra();St();He();_s();UN();import{promises as pX}from"fs";import mX from"path";import{isDeepStrictEqual as Xv}from"util";function cE(e,t){if(typeof e!="string"||e.trim().length===0||e.length>4096)throw new Error(`${t} must be between 1 and 4096 characters`)}Ra();var Ia={root:"/comet/native-runtime",packageKind:"runtime",definition:{apiVersion:"comet/v1alpha1",kind:"Skill",metadata:{name:"comet-native-runtime",version:"3",description:"Comet-owned state runtime for the Native workflow."},goal:{statement:"Advance a Native change only after its current guard passes.",inputs:[],outputs:[],success:["The Native change and Run state agree on the next phase."]},orchestration:{mode:"deterministic",entry:"shape",steps:[{id:"shape",action:{type:"checkpoint"},next:"build"},{id:"build",action:{type:"checkpoint"},next:"verify"},{id:"verify",action:{type:"checkpoint"},next:"archive"},{id:"archive",action:{type:"checkpoint"}}]},skills:[],agents:[],tools:[]},guardrails:{allowedSkills:[],allowedAgents:[],allowedTools:[],maxIterations:Number.MAX_SAFE_INTEGER,maxRetriesPerAction:2,confirmationRequiredFor:[]},evals:[]},lE=Rr("comet-native-runtime:v3:scope-reopen"),fX=[{skillVersion:"3",skillHash:Rr("comet-native-runtime:v3:semantic-repair-budget")},{skillVersion:"2",skillHash:Rr("comet-native-runtime:v2:max-iterations-32")},{skillVersion:"1",skillHash:Rr("comet-native-runtime:v1")}];function mq(e){return e.skillVersion===Ia.definition.metadata.version&&e.skillHash===lE||fX.some(t=>t.skillVersion===e.skillVersion&&t.skillHash===e.skillHash)}var uE={resolveStep({pkg:e,state:t}){return e.definition.orchestration.steps?.find(r=>r.id===t.currentStep)},resolveNext({step:e,outcome:t}){return e.id==="verify"&&t.state?.verification_result==="fail"?"build":e.next??null}};If();Ra();If();async function Jf(e){let r={sequence:(await Ws(e.changeDir,e.run.trajectoryRef)).length+1,timestamp:(e.now??new Date).toISOString(),type:e.type,runId:e.run.runId,data:e.data};return await YD(e.changeDir,e.run.trajectoryRef,r),r}async function Yv(e){let t={runId:e.run.runId,stateVersion:e.run.iteration,trajectoryOffset:e.trajectoryOffset,contextHash:null,artifactsHash:Rr(e.evidenceHash),createdAt:(e.now??new Date).toISOString()};return await XD(e.changeDir,e.run.checkpointRef,t),t}Ra();function hq(e){return Rr(JSON.stringify({summary:e.summary,returnToBuild:e.returnToBuild??!1,confirmed:e.confirmed??!1,artifacts:[...e.artifacts??[]].sort(),noCodeReason:e.noCodeReason??null,verificationResult:e.verificationResult??null,verificationReport:e.verificationReport??null,allowPartialScopeHash:e.allowPartialScopeHash??null,partialReason:e.partialReason??null,repairOverrideSignature:e.repairOverrideSignature??null,repairOverrideSummary:e.repairOverrideSummary??null}))}zg();zd();var Nq=["schema","id","change","evidenceHash","createdAt","previousState","nextState","previousRun","nextRun","eventData"],hX=new Set(Nq),Sq=new Set([...Nq,"minimum_runtime_version","revision"]),gX=new Set([...Sq,"operation"]),pE=new Set(["previousPhase","nextPhase","evidenceHash","summary","artifacts","noCodeReason","verificationResult"]),vX=new Set([...pE,"implementationScopeHash","repairScopeHash","repairStagnation","returnToBuild"]),mE=class extends Error{constructor(r){super(`Native transition for ${r} requires doctor migration before recovery`);this.change=r;this.name="NativeTransitionMigrationRequiredError"}change;code="native-transition-migration-required"};function Eq(e,t){return mX.join(hn(e,t),"transition.json")}function ew(e){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Native transition journal must be an object");return e}function gE(e,t){let r=Object.keys(e).find(n=>!t.has(n));if(r)throw new Error(`Native transition journal contains unknown field: ${r}`)}function Zv(e,t){if(!Number.isSafeInteger(e)||e<1)throw new Error(`${t} must be a positive integer`);return e}function Ki(e,t){return Xv(e,t)}function hE(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Native transition journal event data is invalid");let r=e,n=Object.keys(r),i=n.find(u=>!vX.has(u)),o=[...pE].find(u=>!Object.hasOwn(r,u)),a=pE.size+(Object.hasOwn(r,"implementationScopeHash")?1:0)+(Object.hasOwn(r,"repairScopeHash")?1:0)+(Object.hasOwn(r,"repairStagnation")?1:0)+(Object.hasOwn(r,"returnToBuild")?1:0);if(i||o||n.length!==a)throw new Error(`Native transition journal event data keys are invalid${i?`: ${i}`:o?`: missing ${o}`:""}`);if(!["shape","build","verify","archive"].includes(r.previousPhase)||!["shape","build","verify","archive"].includes(r.nextPhase))throw new Error("Native transition journal event phases are invalid");if(r.evidenceHash!==t)throw new Error("Native transition journal event evidence hash mismatch");if(r.returnToBuild!==void 0&&typeof r.returnToBuild!="boolean")throw new Error("Native transition journal returnToBuild flag is invalid");if(cE(r.summary,"Native transition journal event summary"),jf(r.summary)!==r.summary)throw new Error("Native transition journal event summary contains unredacted credentials");if(!Array.isArray(r.artifacts)||r.artifacts.length>128||r.artifacts.some(u=>typeof u!="string"||u.length===0||Buffer.byteLength(u,"utf8")>512))throw new Error("Native transition journal event artifacts are invalid");if(r.noCodeReason!==null&&(cE(r.noCodeReason,"Native transition journal event no-code reason"),jf(r.noCodeReason)!==r.noCodeReason))throw new Error("Native transition journal event no-code reason contains unredacted credentials");if(r.verificationResult!==null&&r.verificationResult!=="pass"&&r.verificationResult!=="fail")throw new Error("Native transition journal event verification result is invalid");let s=Object.hasOwn(r,"implementationScopeHash")?r.implementationScopeHash:null;if(s!==null&&(typeof s!="string"||!/^[a-f0-9]{64}$/.test(s)||r.previousPhase!=="build"&&r.previousPhase!=="verify"))throw new Error("Native transition journal implementation scope hash is invalid");let c=Object.hasOwn(r,"repairStagnation")?xX(r.repairStagnation):null;if(c){let u=c.overrideSummaryHash===null;if(u&&(r.previousPhase!=="verify"||r.nextPhase!=="build"||r.verificationResult!=="fail")||!u&&(r.previousPhase!=="build"||r.nextPhase!=="verify"||r.verificationResult!==null))throw new Error("Native transition journal repair projection does not match its phase")}let l=Object.hasOwn(r,"repairScopeHash")?r.repairScopeHash:null;if(l!==null&&(typeof l!="string"||!/^[a-f0-9]{64}$/.test(l)||r.previousPhase!=="build"&&r.previousPhase!=="verify"||s===null))throw new Error("Native transition journal repair scope hash is invalid");return{previousPhase:r.previousPhase,nextPhase:r.nextPhase,evidenceHash:t,summary:r.summary,artifacts:[...r.artifacts],noCodeReason:r.noCodeReason,verificationResult:r.verificationResult,...r.returnToBuild===!0?{returnToBuild:!0}:{},...s?{implementationScopeHash:s}:{},...l?{repairScopeHash:l}:{},...c?{repairStagnation:c}:{}}}function wX(e,t){if(e&&typeof e=="object"&&!Array.isArray(e)){let r=e,n=Object.keys(r),i=new Set(["previousPhase","nextPhase","evidenceHash","summary","reason"]);if(n.length===i.size&&n.every(o=>i.has(o))&&r.reason==="spec-rebase")return hE({previousPhase:r.previousPhase,nextPhase:r.nextPhase,evidenceHash:r.evidenceHash,summary:r.summary,artifacts:[],noCodeReason:null,verificationResult:null},t)}return hE(e,t)}function vE(e,t,r=!1){if(e.change!==t)throw new Error("Native transition journal change mismatch");if(typeof e.id!="string"||e.id.length===0)throw new Error("Native transition journal id is invalid");if(typeof e.evidenceHash!="string"||!/^[a-f0-9]{64}$/u.test(e.evidenceHash))throw new Error("Native transition journal evidence hash is invalid");if(typeof e.createdAt!="string"||Number.isNaN(Date.parse(e.createdAt)))throw new Error("Native transition journal timestamp is invalid");let n=r?wX(e.eventData,e.evidenceHash):hE(e.eventData,e.evidenceHash),i=$N(e.nextRun),o=e.previousRun===null?null:$N(e.previousRun);return{id:e.id,evidenceHash:e.evidenceHash,createdAt:e.createdAt,previousRun:o,nextRun:i,eventData:n}}function gq(e,t,r=!1){if(e.skill!==Ia.definition.metadata.name||(r?!mq(e):e.skillVersion!==Ia.definition.metadata.version||e.skillHash!==lE)||e.orchestration!==Ia.definition.orchestration.mode||e.pendingRef!==gi.pendingRef||e.trajectoryRef!==gi.trajectoryRef||e.contextRef!==gi.contextRef||e.artifactsRef!==gi.artifactsRef||e.checkpointRef!==gi.checkpointRef)throw new Error(`Native transition journal ${t} metadata or storage refs are invalid`)}function vq(e){return{runId:e.runId,skill:e.skill,skillVersion:e.skillVersion,skillHash:e.skillHash,orchestration:e.orchestration,pendingRef:e.pendingRef,trajectoryRef:e.trajectoryRef,contextRef:e.contextRef,artifactsRef:e.artifactsRef,checkpointRef:e.checkpointRef,retries:e.retries}}function wq(e,t){if(e.status!=="running")throw new Error(`Native transition journal ${t} status must be running`);if(e.pending!==null)throw new Error(`Native transition journal ${t} pending action must be null`)}function wE(e,t,r,n=!1,i="advance"){let{previousRun:o,nextRun:a}=r;if(gq(a,"next Run",n||o!==null),wq(a,"next Run"),a.runId!==t.run_id||a.currentStep!==t.phase)throw new Error("Native transition journal next Run does not match the next change state");if(i==="runtime-rebuild"){if(o!==null||e.phase==="shape"||t.phase!=="build"||a.iteration!==1||Object.keys(a.retries).length!==0)throw new Error("Native Runtime rebuild Run transition is invalid");return}if(o===null){if(e.run_id!==null||e.phase!=="shape"||a.iteration!==1||Object.keys(a.retries).length!==0)throw new Error("Native transition journal first Run transition is invalid");return}if(gq(o,"previous Run",!0),wq(o,"previous Run"),e.run_id!==o.runId||o.currentStep!==e.phase||t.run_id!==o.runId)throw new Error("Native transition journal previous Run does not match the change state");if(a.iteration!==o.iteration+1)throw new Error("Native transition journal next Run iteration must advance exactly once");if(!Xv(vq(o),vq(a)))throw new Error("Native transition journal Run identity or storage invariants changed")}function yX(e,t,r){return Rr(JSON.stringify({operation:"spec-rebase",change:e,summary:t,specChanges:r}))}function Cq(e,t,r){return e.phase!=="shape"&&t.phase==="build"&&r.verificationResult===null?"spec-rebase":"advance"}function yq(e){return"implementation_scope"in e?{implementation_scope:e.implementation_scope,verification_evidence:e.verification_evidence,partial_allowance:e.partial_allowance}:null}function yE(e,t,r,n,i=!1){let o=r.eventData,a=yq(e),s=yq(t);if(o.previousPhase!==e.phase||o.nextPhase!==t.phase)throw new Error("Native transition journal event phases do not match its states");if(e.archived||t.archived)throw new Error("Native transition journal cannot mutate an archived change");if(n==="runtime-rebuild"){let c=e.name===t.name&&e.language===t.language&&e.brief===t.brief&&e.approval===t.approval&&("approved_contract_hash"in e?"approved_contract_hash"in t&&e.approved_contract_hash===t.approved_contract_hash:!("approved_contract_hash"in t))&&e.created_at===t.created_at&&Xv(e.spec_changes,t.spec_changes);if(e.phase==="shape"||t.phase!=="build"||t.verification_result!=="pending"||t.verification_report!==null||o.verificationResult!==null||o.artifacts.length!==0||o.noCodeReason!==null||!c||s===null||s.implementation_scope!==null||s.verification_evidence!==null||s.partial_allowance!==null)throw new Error("Native Runtime rebuild transition semantics are invalid");return}if(n==="evidence-retreat"){let c=e.name===t.name&&e.language===t.language&&e.brief===t.brief&&e.approval===t.approval&&("approved_contract_hash"in e?"approved_contract_hash"in t&&e.approved_contract_hash===t.approved_contract_hash:!("approved_contract_hash"in t))&&e.created_at===t.created_at&&e.run_id===t.run_id&&Xv(e.spec_changes,t.spec_changes),l=hq({summary:o.summary,...o.returnToBuild?{returnToBuild:!0}:{}});if(!(e.phase==="archive"&&e.verification_result==="pass"||e.phase==="verify"&&e.verification_result==="pending")||t.phase!=="build"||t.verification_result!=="pending"||t.verification_report!==null||o.verificationResult!==null||o.artifacts.length!==0||o.noCodeReason!==null||r.evidenceHash!==l||!c||a===null||s===null||s.implementation_scope!==null||s.verification_evidence!==null||s.partial_allowance!==null)throw new Error("Native transition journal evidence retreat semantics are invalid");return}if(n==="spec-rebase"){let c=yX(e.name,o.summary,t.spec_changes),l=Rr(`spec-rebase:${e.name}:${o.summary}`);if(e.phase==="shape"||t.phase!=="build"||o.verificationResult!==null||o.artifacts.length!==0||o.noCodeReason!==null||t.verification_result!=="pending"||t.verification_report!==null||!i&&r.evidenceHash!==c||i&&r.evidenceHash!==c&&r.evidenceHash!==l||"implementation_scope"in t&&(t.implementation_scope!==null||t.verification_evidence!==null||t.partial_allowance!==null))throw new Error("Native transition journal spec rebase semantics are invalid");return}if(e.phase==="shape"){if(t.phase!=="build"||o.verificationResult!==null||o.artifacts.length!==0||o.noCodeReason!==null||e.verification_result!=="pending"||t.verification_result!=="pending"||e.verification_report!==null||t.verification_report!==null||a!==null&&s!==null&&(a.implementation_scope!==null||a.verification_evidence!==null||a.partial_allowance!==null||s.implementation_scope!==null||s.verification_evidence!==null||s.partial_allowance!==null))throw new Error("Native transition journal Shape to Build semantics are invalid");return}if(e.phase==="build"){if(t.phase!=="verify"||o.verificationResult!==null||o.artifacts.length===0&&o.noCodeReason===null||t.verification_result!=="pending"||t.verification_report!==null||a!==null&&s!==null&&(s.implementation_scope===null||s.verification_evidence!==null||s.implementation_scope!==a.implementation_scope&&s.partial_allowance!==null&&s.partial_allowance===a.partial_allowance))throw new Error("Native transition journal Build to Verify semantics are invalid");return}if(e.phase==="verify"){let c=o.verificationResult==="pass"?"archive":"build";if(o.verificationResult!=="pass"&&o.verificationResult!=="fail"||t.phase!==c||o.artifacts.length!==0||o.noCodeReason!==null||t.verification_result!==o.verificationResult||t.verification_report===null||a!==null&&s!==null&&(a.implementation_scope===null||s.implementation_scope!==a.implementation_scope||s.partial_allowance!==a.partial_allowance||a.verification_evidence!==null||s.verification_evidence===null))throw new Error("Native transition journal Verify outcome semantics are invalid");return}throw new Error("Native transition journal cannot advance from Archive")}function kX(e,t){let r=ew(e);if(gE(r,gX),r.schema!==ol)throw new Error(`Expected Native transition schema ${ol}`);let n=Zv(r.minimum_runtime_version,"Native transition minimum_runtime_version");if(n>3)throw new Error(`Native transition requires runtime protocol ${n}; current protocol is ${3}`);if(n!==3)throw new Error(`Native transition ${ol} minimum_runtime_version must be ${3}`);let i=Zv(r.revision,"Native transition revision");if(i!==1)throw new Error("Native transition journal revision must be 1");if(r.operation!=="advance"&&r.operation!=="spec-rebase"&&r.operation!=="evidence-retreat"&&r.operation!=="runtime-rebuild")throw new Error("Native transition journal operation is invalid");let o=vE(r,t),a=li(r.previousState),s=li(r.nextState);if(a.name!==t||s.name!==t)throw new Error("Native transition journal state mismatch");if(yE(a,s,o,r.operation),wE(a,s,o,!1,r.operation),s.revision!==a.revision+1)throw new Error("Native transition journal state revision must advance exactly once");return{schema:ol,minimum_runtime_version:3,revision:i,operation:r.operation,id:o.id,change:t,evidenceHash:o.evidenceHash,createdAt:o.createdAt,previousState:a,nextState:s,previousRun:o.previousRun,nextRun:o.nextRun,eventData:o.eventData}}function bX(e,t){let r=ew(e);if(gE(r,hX),r.schema!==Jd)throw new Error(`Expected Native transition schema ${Jd}`);let n=vE(r,t,!0),i=pa(r.previousState),o=pa(r.nextState);if(i.name!==t||o.name!==t)throw new Error("Native transition journal state mismatch");return yE(i,o,n,Cq(i,o,n.eventData),!0),wE(i,o,n,!0),{schema:Jd,id:n.id,change:t,evidenceHash:n.evidenceHash,createdAt:n.createdAt,previousState:i,nextState:o,previousRun:n.previousRun,nextRun:n.nextRun,eventData:n.eventData}}function AX(e,t){let r=ew(e);if(gE(r,Sq),r.schema!==al)throw new Error(`Expected Native transition schema ${al}`);if(Zv(r.minimum_runtime_version,"Native v2 transition minimum_runtime_version")!==2)throw new Error(`Native transition ${al} minimum_runtime_version must be 2`);let i=Zv(r.revision,"Native v2 transition revision");if(i!==1)throw new Error("Native v2 transition journal revision must be 1");let o=vE(r,t,!0),a=ma(r.previousState),s=ma(r.nextState);if(a.name!==t||s.name!==t)throw new Error("Native v2 transition journal state mismatch");if(yE(a,s,o,Cq(a,s,o.eventData),!0),wE(a,s,o,!0),s.revision!==a.revision+1)throw new Error("Native v2 transition journal state revision must advance exactly once");return{schema:al,minimum_runtime_version:2,revision:i,id:o.id,change:t,evidenceHash:o.evidenceHash,createdAt:o.createdAt,previousState:a,nextState:s,previousRun:o.previousRun,nextRun:o.nextRun,eventData:o.eventData}}function RX(e,t){let r=ew(e);if(r.schema===ol)return{status:"current",journal:kX(r,t)};if(r.schema===Jd)return{status:"migration-required",journal:bX(r,t)};if(r.schema===al)return{status:"migration-required",journal:AX(r,t)};throw new Error(`Unsupported Native transition journal schema: ${String(r.schema)}`)}async function kE(e,t){let r=Eq(e,t),n=Ve(e,r);await ft(n,r);try{let i=await cr({root:n,file:r,maxBytes:null,label:`Native transition journal ${t}`});return RX(JSON.parse(i.bytes.toString("utf8")),t)}catch(i){if(i.code==="ENOENT")return null;throw i}}async function dE(e,t){let r=await kE(e,t);if(!r)return null;if(r.status==="migration-required")throw new mE(t);return r.journal}function kq(e,t){if(Ki(e,t.nextRun))return"next";if(t.previousRun===null){if(e===null)return"previous"}else if(Ki(e,t.previousRun))return"previous";throw new Error(`Native transition Run content changed for ${t.change}; recovery journal was preserved`)}function bq(e,t){if(Ki(e,t.nextState))return"next";if(Ki(e,t.previousState))return"previous";throw new Error(`Native transition change content changed for ${t.change}; recovery journal was preserved`)}function NX(e){let{journal:t}=e;return _q({sequence:e.sequence,timestamp:t.createdAt,type:e.type,runId:t.nextRun.runId,data:e.type==="run_started"?{runtime:"comet-native",phase:t.previousState.phase,transitionId:t.id}:{...t.eventData,transitionId:t.id}})}function _q(e){return{sequence:e.sequence,timestamp:e.timestamp,type:e.type,runId:e.runId,data:e.data}}function Aq(e,t){let r=e.map((o,a)=>({event:o,index:a})).filter(({event:o})=>o.data.transitionId===t.id),n=r.filter(({event:o})=>o.type==="run_started"),i=r.filter(({event:o})=>o.type==="state_transitioned");if(r.length!==n.length+i.length||n.length>(t.previousRun===null?1:0)||i.length>1||t.previousRun===null&&i.length===1&&(n.length!==1||n[0].index>=i[0].index))throw new Error(`Native trajectory transition id collision for ${t.change}; recovery journal was preserved`);for(let o of[...n,...i]){let a=NX({sequence:o.index+1,journal:t,type:o.event.type});if(!Ki(_q(o.event),a))throw new Error(`Native trajectory event changed for transition ${t.id}; recovery journal was preserved`)}return{started:n[0]?.event??null,transitioned:i[0]?.event??null}}async function Iq(e,t,r){if(await Xg(e,t))throw new Error(`Native schema migration is incomplete for ${t}; run doctor --repair`);await Jg(e,t);let n=await dE(e,t);if(!n)return null;let i=hn(e,t),o=Aq(await Ws(i,n.nextRun.trajectoryRef),n),[a,s]=await Promise.all([Sl(i),Aa(e,t)]),c=kq(a,n),l=bq(s,n);if((o.started||o.transitioned)&&(c!=="next"||l!=="next"))throw new Error(`Native trajectory is ahead of transition state for ${n.change}; recovery journal was preserved`);if(c==="previous"&&(await Hg(i,n.nextRun),await r?.afterRunStateWritten?.(n)),!Ki(await Sl(i),n.nextRun))throw new Error(`Native transition Run content changed while continuing ${n.change}; recovery journal was preserved`);if(l==="previous"){let g=await pB(e,n.nextState,n.previousState.revision);if(!Ki(g,n.nextState))throw new Error(`Native transition change write diverged for ${n.change}; recovery journal was preserved`);await r?.afterChangeStateWritten?.(n)}if(!Ki(await Aa(e,t),n.nextState))throw new Error(`Native transition change content changed while continuing ${n.change}; recovery journal was preserved`);let u=await dE(e,t);if(!u||!Ki(u,n))throw new Error(`Native transition journal changed while continuing ${n.change}; it was preserved`);let f=Aq(await Ws(i,n.nextRun.trajectoryRef),n);n.previousRun===null&&(f.started||await Jf({changeDir:i,run:n.nextRun,type:"run_started",data:{runtime:"comet-native",phase:n.previousState.phase,transitionId:n.id},now:new Date(n.createdAt)}));let d=f.transitioned;d||(d=await Jf({changeDir:i,run:n.nextRun,type:"state_transitioned",data:{...n.eventData,transitionId:n.id},now:new Date(n.createdAt)})),await Yv({changeDir:i,run:n.nextRun,trajectoryOffset:d.sequence,evidenceHash:n.evidenceHash,now:new Date(n.createdAt)});let[p,m]=await Promise.all([Sl(i),Aa(e,t)]);kq(p,{...n,previousRun:n.nextRun}),bq(m,{...n,previousState:n.nextState});let h=await dE(e,t);if(!h||!Ki(h,n))throw new Error(`Native transition journal changed while continuing ${n.change}; it was not removed`);return await pX.rm(Eq(e,t),{force:!0}),n.nextState}var xq={maxFailedAcceptanceIds:1024,maxFailedCheckIds:128},SX=/^[a-f0-9]{64}$/u,Rq=["disposition","overrideSummaryHash","signatureHash"],EX=["contractHash","disposition","failedAcceptanceIds","failedCheckIds","maxVerifyFailures","overrideSummaryHash","signatureHash"];function tw(e,t){return e<t?-1:e>t?1:0}function CX(e,t,r){let n=Object.keys(e).sort(tw);if(n.length!==t.length||n.some((i,o)=>i!==t[o]))throw new Error(`${r} fields are invalid`)}function _X(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);let r=Object.getPrototypeOf(e);if(r!==Object.prototype&&r!==null)throw new Error(`${t} must be a plain object`);return e}function fE(e,t){if(typeof e!="string"||!SX.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function IX(e){if(!Array.isArray(e)||e.length>xq.maxFailedAcceptanceIds||e.some(t=>typeof t!="string"||!/^acceptance-[a-f0-9]{64}$/u.test(t)))throw new Error("Native repair trajectory failed acceptance IDs are invalid");return[...new Set(e)].sort(tw)}function xX(e){let t=_X(e,"Native repair trajectory projection"),r=Object.keys(t).sort(tw),n=r.length===Rq.length&&r.every((l,u)=>l===Rq[u]);n||CX(t,EX,"Native repair trajectory projection");let i=fE(t.signatureHash,"Native repair trajectory signature hash");if(t.disposition!=="continue"&&t.disposition!=="warn"&&t.disposition!=="manual-stop"&&t.disposition!=="hard-stop")throw new Error("Native repair trajectory disposition is invalid");let o=t.overrideSummaryHash===null?null:fE(t.overrideSummaryHash,"Native repair trajectory override summary hash");if(o!==null&&t.disposition!=="continue")throw new Error("Native repair trajectory override must continue exactly once");if(n)return{signatureHash:i,disposition:t.disposition,overrideSummaryHash:o,contractHash:null,failedAcceptanceIds:[],failedCheckIds:[],maxVerifyFailures:null};let a=fE(t.contractHash,"Native repair trajectory contract hash"),s=IX(t.failedAcceptanceIds),c=OX(t.failedCheckIds);if(!Number.isSafeInteger(t.maxVerifyFailures)||t.maxVerifyFailures<1)throw new Error("Native repair trajectory maximum Verify failures is invalid");return{signatureHash:i,disposition:t.disposition,overrideSummaryHash:o,contractHash:a,failedAcceptanceIds:s,failedCheckIds:c,maxVerifyFailures:t.maxVerifyFailures}}var PX=/^[a-z0-9][a-z0-9._:/-]{0,255}$/u;function TX(e,t,r,n){if(!Array.isArray(e)||e.length>r||!n&&e.length===0)throw new Error(`${t} exceeds its count boundary`);let i=e.map(o=>{if(typeof o!="string"||!PX.test(o))throw new Error(`${t} contains an invalid token: ${String(o)}`);return o});return[...new Set(i)].sort(tw)}function OX(e=[]){return TX(e,"Native repair failed check IDs",xq.maxFailedCheckIds,!0)}async function $X(e,t){await Cn(e.projectRoot);let r=Nx(e,t),n=Rc(e,t);for(let i of["workspace.json","supervisor/state.json"])await pq(e.projectRoot,rw.relative(e.projectRoot,rw.join(r,i)).replaceAll("\\","/"),e.workspaceRuntimeRoot,rw.relative(e.workspaceRuntimeRoot,rw.join(n,i)).replaceAll("\\","/"))}async function DX(e,t){let r=await Mn(e,{kind:"migration",change:t});return r?.kind==="migration"?r.journal:null}async function Pq(e,t){await $q.mkdir(e.transactionsDir,{recursive:!0}),await Bt(Ss(e,{kind:"migration",change:t.change}),t,{containedRoot:e.runtimeDir})}async function Tq(e,t){try{let r=await El(e,t);if(r?.schema==="comet.native.workspace.v3")return{isolation:r.isolation,change_branch:r.changeBranch,target_branch:r.targetBranch,finish:r.finish}}catch{}return{isolation:"current",change_branch:null,target_branch:null,finish:null}}function Oq(e,t){if(t.isolation==="current"&&t.change_branch===null)return;let r=ue(e.projectRoot);if(!r.isGitWorktree)throw new Error("Native legacy migration requires its bound Git branch or worktree");if(r.currentBranch!==t.change_branch)throw new Error(`Native legacy migration expected branch ${t.change_branch??"(missing)"}, current branch is ${r.currentBranch??"(detached)"}`);if(t.isolation==="worktree"&&!r.isSecondaryWorktree)throw new Error("Native legacy migration requires its bound linked worktree")}async function BX(e){let t=Fi(e.paths,e.state.name),r=await Pe({root:t,ref:e.state.brief,maxBytes:null,includeHash:!1}),n=[];for(let i of e.state.spec_changes){if(i.operation==="remove"||!i.source)continue;let o=await Pe({root:t,ref:i.source,maxBytes:null,includeHash:!1});n.push({capability:i.capability,source:o.ref,markdown:o.text})}try{return lg({briefMarkdown:r.text,specs:n})}catch(i){if(e.state.phase==="shape"&&i.message.includes("at least one acceptance"))return[];throw i}}async function jq(e,t){let r=await Tf(e,t);if(r.status==="runtime-incompatible")throw new ci(r.schema,r.minimumRuntimeVersion);if(!r.state)throw new Error(`Native legacy change ${t} is unreadable`);return r.state}async function bE(e){return await $X(e.paths,e.name),$e(e.paths,async()=>{let t=await DX(e.paths,e.name),r=await Ps(e.paths,e.name)?await Jt(Pt(e.paths,e.name)):null;if(!t&&!r&&await Iq(e.paths,e.name),!t&&r)return r;let n=null,i=null;for(t||(n=await jq(e.paths,e.name),i=await Tq(e.paths,e.name),Oq(e.paths,i),t={schema:ug,id:jX(),change:n.name,fromSchema:n.schema,status:"prepared",createdAt:(e.now??new Date).toISOString()},await Pq(e.paths,t));;){let o=D0(t);if(o.action==="done")break;o.action==="commit-portable-yaml"?r||(n??=await jq(e.paths,e.name),i??=await Tq(e.paths,e.name),Oq(e.paths,i),r=$0({state:n,acceptance:await BX({paths:e.paths,state:n}),workspace:i,migratedAt:e.now}),await $d(Pt(e.paths,e.name),r,{containedRoot:e.paths.nativeRoot})):o.action==="cleanup-legacy-runtime"?r??=await Jt(Pt(e.paths,e.name)):o.action==="commit-transaction"&&(r??=await Jt(Pt(e.paths,e.name))),t={...t,status:o.nextStatus},await Pq(e.paths,t)}return await $q.rm(Ss(e.paths,{kind:"migration",change:e.name}),{force:!0}),r??Jt(Pt(e.paths,e.name))},{allowedPortableTransaction:{kind:"migration",change:e.name}})}Er();Qc();dt();Et();He();_s();vl();Pf();import{createHash as WX,randomUUID as YNe}from"crypto";import{promises as Gf}from"fs";import Gt from"path";async function un(e){try{return await Gf.access(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function qX(e){let t;try{t=await Gf.readdir(e.changesDir,{withFileTypes:!0})}catch(r){if(r.code==="ENOENT")return;throw r}for(let r of t.sort((n,i)=>n.name.localeCompare(i.name))){if(!r.isDirectory()||r.isSymbolicLink())continue;let n=await El(e,r.name);if(n){await uB({paths:e,name:r.name,revision:n.capturedRevision,...n.schema==="comet.native.workspace.v3"?{binding:{isolation:n.isolation,changeBranch:n.changeBranch,targetBranch:n.targetBranch},...n.finish?{finish:n.finish}:{}}:{}});continue}}}async function Kf(e,t){let r=[];async function n(i){let o=await yo({root:e,directory:i,label:"Native root tree"}),a=o.entries;a.sort((s,c)=>s.name.localeCompare(c.name));for(let s of a){await o.verify();let c=Gt.join(i,s.name),l=await Gf.lstat(c);if(s.isSymbolicLink()||l.isSymbolicLink()){if(t.rejectSymlinks)throw new Error(`Native root contains a symlink: ${c}`);await o.verify();continue}if(s.isDirectory()&&l.isDirectory())r.push({ref:Gt.relative(e,c).split(Gt.sep).join("/"),type:"directory"}),await n(c);else if(s.isFile()&&l.isFile()){let u=await lf({root:e,file:c,label:`Native root file ${Gt.relative(e,c)}`});r.push({ref:Gt.relative(e,c).split(Gt.sep).join("/"),type:"file",size:u.size,hash:u.hash})}else throw new Error(`Native root contains an unsupported file type: ${c}`);await o.verify()}}return await n(e),r.sort((i,o)=>i.ref.localeCompare(o.ref))}async function LX(e,t,r){await Li({root:r,directory:t,label:"Native root move staging directory"});async function n(i,o){let a=await yo({root:e,directory:i,label:"Native root move source directory"}),s=a.entries;for(let c of s){await a.verify();let l=Gt.join(i,c.name),u=await Gf.lstat(l);if(c.isSymbolicLink()||u.isSymbolicLink())throw new Error(`Native root contains a symlink: ${l}`);let f=Gt.join(o,c.name);if(c.isDirectory()&&u.isDirectory())await Li({root:r,directory:f,label:"Native root move staging directory"}),await n(l,f);else if(c.isFile()&&u.isFile())await Cs({sourceRoot:e,source:l,targetRoot:r,target:f,maxBytes:null,label:`Native root move file ${Gt.relative(e,l)}`,exclusive:!0,expectedTargetHash:null});else throw new Error(`Native root contains an unsupported file type: ${l}`);await a.verify()}}await n(e,t)}async function Vl(e,t){let r=await Kf(e,{rejectSymlinks:!0}),n=await Kf(t,{rejectSymlinks:!0});if(JSON.stringify(r)!==JSON.stringify(n))throw new Error(`Native root copies differ; preserve both trees for manual recovery: ${e} and ${t}`)}function VX(e,t){return Gt.join(e.artifactRoot,`.comet-native-move-${t}`)}function MX(e,t){return Gt.join(e.artifactRoot,`.comet-native-source-${t}.removing`)}function FX(e){return`${e}.removing`}function Dq(e,t){return Gt.join(Gt.dirname(e),`.${Gt.basename(e)}.${t}.rollback-removing`)}function qq(e,t,r){return Gt.join(yg(e,t).directory,`root-move-cleanup-${r}.json`)}function HX(e){return JSON.stringify(e,null,2)+`
|
|
471
|
+
`}function QX(e){return WX("sha256").update(e).digest("hex")}function UX(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`Native root-move cleanup manifest entry ${t} must be an object`);let r=e,n=Object.keys(r).sort(),i=r.type==="file"?["hash","ref","size","type"]:["ref","type"];if(JSON.stringify(n)!==JSON.stringify(i))throw new Error(`Native root-move cleanup manifest entry ${t} has invalid fields`);if(typeof r.ref!="string"||r.ref.length===0||r.ref.includes("\\")||Gt.posix.normalize(r.ref)!==r.ref||r.ref.startsWith("/")||r.ref.split("/").includes("..")||Buffer.byteLength(r.ref,"utf8")>4096)throw new Error(`Native root-move cleanup manifest entry ${t} has an invalid ref`);if(r.type==="directory")return{ref:r.ref,type:"directory"};if(r.type!=="file"||typeof r.size!="number"||!Number.isSafeInteger(r.size)||r.size<0||typeof r.hash!="string"||!/^[a-f0-9]{64}$/u.test(r.hash))throw new Error(`Native root-move cleanup manifest entry ${t} is invalid`);return{ref:r.ref,type:"file",size:r.size,hash:r.hash}}function JX(e,t,r){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Native root-move cleanup manifest must be an object");let n=e;if(JSON.stringify(Object.keys(n).sort())!==JSON.stringify(["entries","kind","schema","transactionId"])||n.schema!=="comet.native.root-move-cleanup.v1"||n.transactionId!==t||n.kind!==r||!Array.isArray(n.entries))throw new Error("Native root-move cleanup manifest binding is invalid");let i=n.entries.map(UX);for(let o=0;o<i.length;o+=1){if(o>0&&i[o-1].ref.localeCompare(i[o].ref)>=0)throw new Error("Native root-move cleanup manifest refs must be unique and sorted");let a=Gt.posix.dirname(i[o].ref);if(a!=="."&&!i.some(s=>s.ref===a&&s.type==="directory"))throw new Error(`Native root-move cleanup manifest parent is missing: ${a}`)}return{schema:"comet.native.root-move-cleanup.v1",transactionId:t,kind:r,entries:i}}async function zX(e){let t={schema:"comet.native.root-move-cleanup.v1",transactionId:e.id,kind:e.kind,entries:e.entries},r=HX(t);return await qe(qq(e.paths,e.id,e.kind),r,{containedRoot:e.paths.runtimeDir}),QX(r)}async function KX(e){let t=await cr({root:e.paths.runtimeDir,file:qq(e.paths,e.id,e.cleanup.kind),maxBytes:null,label:`Native root-move cleanup manifest ${e.cleanup.kind}`});if(t.hash!==e.cleanup.manifestHash)throw new Error("Native root-move cleanup manifest hash changed");return JX(JSON.parse(t.bytes.toString("utf8")),e.id,e.cleanup.kind)}async function AE(e){let t=await Kf(e.quarantine,{rejectSymlinks:!0}),r=new Map(e.manifest.entries.map(n=>[n.ref,n]));for(let n of t){let i=r.get(n.ref);if(!i||JSON.stringify(i)!==JSON.stringify(n))throw new Error(`Native root-move cleanup quarantine differs from its bound manifest: ${n.ref}`)}if(e.exact&&t.length!==e.manifest.entries.length)throw new Error("Native root-move cleanup quarantine is incomplete before deletion");return t}function Bq(e){return e.ref.split("/").length}async function GX(e){let r=[...await AE({quarantine:e.quarantine,manifest:e.manifest,exact:!1})].sort((i,o)=>Bq(o)-Bq(i)||(i.type===o.type?o.ref.localeCompare(i.ref):i.type==="file"?-1:1)),n=0;for(let i of r){let o=Gt.join(e.quarantine,...i.ref.split("/"));i.type==="file"?await pg({root:e.projectRoot,file:o,maxBytes:null,expectedHash:i.hash,expectedSize:i.size,label:`Native root-move cleanup file ${i.ref}`}):await FR({root:e.projectRoot,directory:o,label:`Native root-move cleanup directory ${i.ref}`}),n+=1,await e.hooks?.afterRootMoveCleanupEntryRemoved?.(e.manifest.kind,i.ref,n)}await AE({quarantine:e.quarantine,manifest:e.manifest,exact:!1}),await FR({root:e.projectRoot,directory:e.quarantine,label:`Native root-move cleanup quarantine ${e.manifest.kind}`})}function Lq(e,t,r=e.native.artifact_root){return{...e,native:{...e.native,artifact_root:r,pending_root_move:t}}}function YX(e){return{schema:"comet.native.transaction.v1",id:e.id,kind:"root-move",status:"prepared",projectRoot:e.paths.projectRoot,nativeRoot:e.paths.nativeRoot,createdAt:e.now.toISOString(),operations:[]}}async function XX(e,t,r,n){for(let o of[e,t])try{let a=await Hn(o,n);if(a.kind!=="root-move")throw new Error(`Transaction ${n} is not a root move`);return{journal:a,paths:o}}catch(a){if(a.code!=="ENOENT")throw a}let i=Gt.join(r,"runtime","transactions",n,"transaction.json");try{let o=await cr({root:r,file:i,maxBytes:null,label:`Staged Native root-move journal ${n}`}),a=JSON.parse(o.bytes.toString("utf8"));if(a.schema!=="comet.native.transaction.v1"||a.kind!=="root-move")throw new Error(`Invalid staged root-move journal: ${n}`);return{journal:a,paths:t}}catch(o){throw o.code!=="ENOENT"?o:new Error(`Native root-move journal is missing: ${n}`,{cause:o})}}async function Wq(e){let t=Lq(e.config,{...e.pending,stage:e.stage},e.activeArtifactRoot);return await no(e.projectRoot,t),t}async function zf(e){let t=e.config.native.pending_root_move;if(!t||t.id!==e.id)throw new Error(`Native root-move cleanup ${e.id} lost its pending configuration`);let r=Lq(e.config,{id:t.id,fromArtifactRoot:t.fromArtifactRoot,toArtifactRoot:t.toArtifactRoot,stage:t.stage,...e.cleanup?{cleanup:e.cleanup}:{}},e.config.native.artifact_root);return await no(e.projectRoot,r),r}async function nw(e){let t=e.config,r=t.native.pending_root_move;if(!r||r.id!==e.id)throw new Error(`Native root-move cleanup ${e.id} lost its pending configuration`);let n=r.cleanup;if(n&&n.kind!==e.kind)throw new Error(`Native root move has unfinished ${n.kind} cleanup; cannot start ${e.kind}`);let i=await un(e.target),o=await un(e.quarantine);if(i&&o)throw new Error(`Native root-move cleanup target and quarantine both exist: ${e.kind}`);if(!n){if(!i&&!o)return t;if(!i&&o)throw new Error(`Native root-move cleanup quarantine is not transaction-bound: ${e.kind}`);let s=await zX({paths:e.stablePaths,id:e.id,kind:e.kind,entries:await Kf(e.target,{rejectSymlinks:!0})});n={kind:e.kind,state:"prepared",manifestHash:s},t=await zf({projectRoot:e.projectRoot,config:t,id:e.id,cleanup:n})}let a=await KX({paths:e.stablePaths,id:e.id,cleanup:n});if(i=await un(e.target),o=await un(e.quarantine),i&&o)throw new Error(`Native root-move cleanup target and quarantine both exist: ${e.kind}`);if(i){if(n.state!=="prepared")throw new Error(`Native root-move cleanup target reappeared after quarantine: ${e.kind}`);await H0({root:e.projectRoot,directory:e.target,quarantine:e.quarantine,label:e.label,beforeQuarantine:e.beforeQuarantine,afterQuarantine:e.afterQuarantine}),o=!0}if(!o){if(n.state!=="deleting")throw new Error(`Native root-move cleanup quarantine disappeared: ${e.kind}`);return zf({projectRoot:e.projectRoot,config:t,id:e.id})}return await AE({quarantine:e.quarantine,manifest:a,exact:n.state!=="deleting"}),n.state==="prepared"&&(n={...n,state:"quarantined"},t=await zf({projectRoot:e.projectRoot,config:t,id:e.id,cleanup:n})),n.state==="quarantined"&&(n={...n,state:"deleting"},t=await zf({projectRoot:e.projectRoot,config:t,id:e.id,cleanup:n})),await GX({projectRoot:e.projectRoot,quarantine:e.quarantine,manifest:a,hooks:e.hooks}),zf({projectRoot:e.projectRoot,config:t,id:e.id})}async function ZX(e){let t=e.config,r=t.native.pending_root_move.stage;if(r==="copying"){if(!await un(e.sourcePaths.nativeRoot))throw new Error(`Native source root is missing: ${e.sourcePaths.nativeRoot}`);let s=FX(e.staging);t=await nw({projectRoot:e.projectRoot,config:t,id:e.pending.id,kind:"restart-staging",stablePaths:e.sourcePaths,target:e.staging,quarantine:s,label:"Native root move stale staging removal",hooks:e.hooks}),await Kf(e.sourcePaths.nativeRoot,{rejectSymlinks:!0}),await LX(e.sourcePaths.nativeRoot,e.staging,e.destinationPaths.projectRoot),await Vl(e.sourcePaths.nativeRoot,e.staging),t=await Wq({projectRoot:e.projectRoot,config:t,pending:e.pending,stage:"ready"}),r="ready",await e.hooks?.afterRootMoveStage?.("ready",e.journal)}if(r==="ready"){if(await un(e.destinationPaths.nativeRoot)){if(await un(e.staging))throw new Error(`Native destination is occupied: ${e.destinationPaths.nativeRoot}`);await Vl(e.sourcePaths.nativeRoot,e.destinationPaths.nativeRoot)}else{if(!await un(e.staging))throw new Error("Native move staging tree is missing");await Vl(e.sourcePaths.nativeRoot,e.staging),await Gf.rename(e.staging,e.destinationPaths.nativeRoot)}t=await Wq({projectRoot:e.projectRoot,config:t,pending:e.pending,stage:"switched",activeArtifactRoot:e.pending.toArtifactRoot}),r="switched",await e.hooks?.afterRootMoveStage?.("switched",e.journal)}if(r!=="switched")throw new Error(`Unsupported Native root-move stage: ${r}`);if(!await un(e.destinationPaths.nativeRoot))throw new Error(`Native destination root is missing: ${e.destinationPaths.nativeRoot}`);let n=MX(e.sourcePaths,e.pending.id);!t.native.pending_root_move?.cleanup&&await un(e.sourcePaths.nativeRoot)&&await Vl(e.sourcePaths.nativeRoot,e.destinationPaths.nativeRoot),t=await nw({projectRoot:e.projectRoot,config:t,id:e.pending.id,kind:"forward-source",stablePaths:e.destinationPaths,target:e.sourcePaths.nativeRoot,quarantine:n,label:"Native root move source removal",beforeQuarantine:()=>e.hooks?.beforeRootMoveSourceRemove?.(e.sourcePaths.nativeRoot),afterQuarantine:s=>e.hooks?.afterRootMoveSourceQuarantined?.(s),hooks:e.hooks}),await qX(e.destinationPaths);let i=await Hn(e.destinationPaths,e.pending.id);await gl(e.destinationPaths,i,"commit");let o={artifact_root:t.native.artifact_root,language:t.native.language,clarification_mode:t.native.clarification_mode,archive_confirmation:t.native.archive_confirmation,max_verify_failures:t.native.max_verify_failures,max_parallel_children:t.native.max_parallel_children},a={...t,native:{...o,artifact_root:e.pending.toArtifactRoot}};return await no(e.projectRoot,a),a}async function Vq(e){let t=await Te(e.projectRoot),r=t?.native.pending_root_move;if(!t||!r)throw new Error("No pending Native root move was found");let n=await we(e.projectRoot,r.fromArtifactRoot),i=await we(e.projectRoot,r.toArtifactRoot),o=VX(i,r.id),a;try{a=await XX(n,i,o,r.id)}catch(d){if(r.stage!=="copying"||!await un(n.nativeRoot))throw d;let p=YX({id:r.id,paths:n,now:new Date});await Z0(n,p),a={journal:p,paths:n}}if(e.strategy==="continue"){let d=await ZX({projectRoot:e.projectRoot,config:t,pending:r,sourcePaths:n,destinationPaths:i,staging:o,journal:a.journal,hooks:e.hooks});return{activeNativeRoot:i.nativeRoot,config:d}}if(!await un(n.nativeRoot))throw new Error("Cannot roll back after the old Native root was removed; continue recovery");let s=Dq(i.nativeRoot,r.id);!t.native.pending_root_move?.cleanup&&await un(i.nativeRoot)&&await Vl(n.nativeRoot,i.nativeRoot),(!t.native.pending_root_move?.cleanup||t.native.pending_root_move.cleanup.kind==="rollback-destination")&&(t=await nw({projectRoot:e.projectRoot,config:t,id:r.id,kind:"rollback-destination",stablePaths:n,target:i.nativeRoot,quarantine:s,label:"Native root move rollback destination removal",hooks:e.hooks}));let c=Dq(o,r.id);!t.native.pending_root_move?.cleanup&&await un(o)&&await Vl(n.nativeRoot,o),(!t.native.pending_root_move?.cleanup||t.native.pending_root_move.cleanup.kind==="rollback-staging")&&(t=await nw({projectRoot:e.projectRoot,config:t,id:r.id,kind:"rollback-staging",stablePaths:n,target:o,quarantine:c,label:"Native root move rollback staging removal",hooks:e.hooks}));let l=await Hn(n,r.id);await kg(n,l);let u={artifact_root:t.native.artifact_root,language:t.native.language,clarification_mode:t.native.clarification_mode,archive_confirmation:t.native.archive_confirmation,max_verify_failures:t.native.max_verify_failures,max_parallel_children:t.native.max_parallel_children},f={...t,native:{...u,artifact_root:r.fromArtifactRoot}};return await no(e.projectRoot,f),{activeNativeRoot:n.nativeRoot,config:f}}Et();import Fl from"path";import{isDeepStrictEqual as RZ}from"util";import{createHash as eZ}from"crypto";function Mq(e,t,r,n){return t.iteration>=r.maxIterations?{allowed:!1,reason:`Iteration budget exhausted: ${r.maxIterations}`}:e.type==="invoke_skill"&&!r.allowedSkills.includes(e.ref??"")?{allowed:!1,reason:`Skill is not allowed: ${e.ref??"(missing)"}`}:e.type==="call_tool"&&!r.allowedTools.includes(e.ref??"")?{allowed:!1,reason:`Tool is not allowed: ${e.ref??"(missing)"}`}:e.type==="handoff"&&!r.allowedAgents.includes(e.ref??"")?{allowed:!1,reason:`Agent is not allowed: ${e.ref??"(missing)"}`}:e.ref&&r.confirmationRequiredFor.includes(e.ref)&&!n.has(e.ref)?{allowed:!1,reason:`User confirmation required for: ${e.ref}`}:(t.retries[e.id]??0)>r.maxRetriesPerAction?{allowed:!1,reason:`Retry budget exhausted for action: ${e.id}`}:{allowed:!0}}function Fq(e){if(e===null||typeof e!="object"||Object.isFrozen(e))return e;for(let t of Reflect.ownKeys(e))Fq(e[t]);return Object.freeze(e)}function xa(e){return Fq(structuredClone(e))}function RE(e,t,r,n){return e.resolveStep({pkg:xa(t),state:xa(r),context:xa(n)})}function Hq(e,t,r,n,i,o){return e.resolveNext({pkg:xa(t),state:xa(r),step:xa(n),outcome:xa(i),context:xa(o)})}function tZ(e,t,r){return eZ("sha256").update(`${e}:${t}:${r??"adaptive"}`).digest("hex").slice(0,16)}function NE(e,t){return e.definition.orchestration.steps?.find(r=>r.id===t)}function Qq(e,t,r,n,i){if(t.status!=="running")return{state:t,action:null,reason:`Run is ${t.status}`};if(t.pending)return{state:t,action:null,reason:`Action already pending: ${t.pending}`};if(t.orchestration==="adaptive")return{state:t,action:null,reason:"Adaptive orchestration requires an Agent candidate"};let o=RE(n,e,t,i);if(!o&&t.currentStep===null)return{state:{...t,status:"completed"},action:null};if(!o)return{state:{...t,status:"failed"},action:null,reason:`Unknown current step: ${t.currentStep}`};let a=NE(e,o.id);if(!a)return{state:{...t,status:"failed"},action:null,reason:`Resolver returned unknown current step: ${o.id}`};let s=t.currentStep===a.id?t:{...t,currentStep:a.id},c={...a.action,id:tZ(s.runId,s.iteration,a.id),stepId:a.id};return rZ(e,s,c,r)}function rZ(e,t,r,n){let i=Mq(r,t,e.guardrails,n);return i.allowed?{state:{...t,pending:r.id,status:"waiting"},action:r}:{state:t,action:null,reason:i.reason}}function Uq(e,t,r,n,i){if(!t.pending||t.pending!==r.actionId)throw new Error(`Outcome does not match pending action: ${r.actionId}`);let o=t.orchestration==="deterministic"?RE(n,e,t,i):void 0,a=o?NE(e,o.id):void 0;if(t.orchestration==="deterministic"&&!o)throw new Error(`Unknown current step: ${t.currentStep??"(missing)"}`);if(t.orchestration==="deterministic"&&!a)throw new Error(`Resolver returned unknown current step: ${o.id}`);if(r.status==="failed"){let c={...t.retries,[r.actionId]:(t.retries[r.actionId]??0)+1};return{...t,pending:null,status:"running",retries:c}}let s=t.orchestration==="deterministic"?Hq(n,e,t,a,r,i):t.currentStep;if(s!==null&&t.orchestration==="deterministic"&&!NE(e,s))throw new Error(`Resolver returned unknown next step: ${s}`);return{...t,currentStep:s,iteration:t.iteration+1,pending:null,status:s===null&&t.orchestration==="deterministic"?"completed":"running"}}If();Ra();_s();import{promises as SE}from"node:fs";import _o from"node:path";var nZ="comet.native.archive-tree.v1",iZ={maxDepth:128,maxEntries:2e4};function Kq(e){let t={...iZ,...e};for(let[r,n]of Object.entries(t))if(!Number.isSafeInteger(n)||n<=0)throw new Error(`Native Archive content limit ${r} must be a positive safe integer`);return t}function Jq(e){return JSON.stringify(e.map(t=>({name:t.name,kind:t.isDirectory()?"directory":t.isFile()?"file":t.isSymbolicLink()?"symlink":"other"})).sort((t,r)=>t.name.localeCompare(r.name)))}function zq(e,t,r,n){if(r.entryCount+=1,r.entryCount>n.maxEntries)throw new Error(`Native Archive content exceeds ${n.maxEntries} entries`);e.push(t)}async function Gq(e,t,r,n,i,o){if(o>i.maxDepth)throw new Error(`Native Archive content exceeds depth ${i.maxDepth}`);let a=await yo({root:e,directory:t,label:`Native Archive content directory ${_o.relative(e,t)||"."}`,maxEntries:i.maxEntries}),s=Jq(a.entries),c=[...a.entries];c.sort((u,f)=>u.name.localeCompare(f.name));for(let u of c){await a.verify();let f=_o.join(t,u.name),d=_o.relative(e,f).replaceAll("\\","/"),p=await SE.lstat(f);if(u.isSymbolicLink()||p.isSymbolicLink())throw new Error(`Native Archive content must not contain symlinks or junctions: ${d}`);if(u.isDirectory()&&p.isDirectory()){zq(r,{ref:d,kind:"directory"},n,i),await Gq(e,f,r,n,i,o+1);continue}if(!u.isFile()||!p.isFile())throw new Error(`Native Archive content must contain only files and directories: ${d}`);let m=await lf({root:e,file:f,label:`Native Archive content file ${d}`});zq(r,{ref:d,kind:"file",hash:m.hash,size:m.size},n,i),await a.verify()}await a.verify();let l=await yo({root:e,directory:t,label:`Native Archive content directory ${_o.relative(e,t)||"."}`,maxEntries:i.maxEntries});if(Jq(l.entries)!==s)throw new Error(`Native Archive content directory changed while reading: ${_o.relative(e,t)||"."}`);await Promise.all([a.verify(),l.verify()])}async function oZ(e,t={}){let r=Kq(t);e=_o.resolve(e);let n=await SE.lstat(e);if(!n.isDirectory()||n.isSymbolicLink())throw new Error(`Native Archive move source must be a real directory: ${e}`);let i=[];await Gq(e,e,i,{entryCount:0},r,0);let a=JSON.stringify(i);return Rr(`${nZ}\0${a}`)}async function wi(e,t={}){let r=Kq(t);e=_o.resolve(e);let n;try{n=await SE.lstat(e)}catch(i){if(i.code==="ENOENT")return null;throw i}if(n.isSymbolicLink())throw new Error(`Native Archive transaction path must not be a symlink or junction: ${e}`);if(n.isFile())return{kind:"file",hash:(await lf({root:_o.dirname(e),file:e,label:`Native Archive transaction file ${_o.basename(e)}`})).hash};if(n.isDirectory())return{kind:"directory",hash:await oZ(e,r)};throw new Error(`Native Archive transaction path has an unsupported file type: ${e}`)}Du();dt();hc();import{promises as Mr}from"node:fs";import gt from"node:path";He();_s();vl();var Yf="comet.native.archive-cas.v1";function aZ(e,t){let r=zR(e,t);if(r)return r;let n="runtime/",i=t.startsWith(n),o=i?e.runtimeDir:e.nativeRoot,a=i?t.slice(n.length):t,s=gt.resolve(o,...a.split("/"));if(!yt(o,s))throw new Error(`Unsafe Native Archive transaction ref: ${t}`);return s}async function tr(e,t){let r=aZ(e,t);return ft(Ve(e,r),r)}function Pa(e,t,r="file"){return t===null?e===null:e?.kind===r&&e.hash===t}function Ml(e){return e===null?"missing":`${e.kind}:${e.hash}`}async function dn(e){let t=await wi(e.target);if(!Pa(t,e.expectedHash,e.expectedKind))throw new Error(`${e.label} content changed: expected ${e.expectedHash??"missing"}, got ${Ml(t)}`);return t}async function CE(e,t){let r=await ko(e,t),n=await cr({root:e.runtimeDir,file:r.journal,maxBytes:null,label:`Native Archive transaction journal ${t}`}),i=wg(JSON.parse(n.bytes.toString("utf8")));if(i.id!==t)throw new Error(`Invalid Native Archive transaction journal: ${t}`);return i}async function iw(e,t,r){let n=wg({...t,status:r}),i=await ko(e,n.id);return await Bt(i.journal,n,{containedRoot:e.runtimeDir}),(r==="committed"||r==="rolled-back")&&await pf(e,t.id),n}function ow(e){return{dev:e.dev,ino:e.ino,birthtimeMs:e.birthtimeMs}}function Yq(e){return{...ow(e),ctimeMs:e.ctimeMs,mtimeMs:e.mtimeMs,size:e.size}}function Ta(e,t){return ot({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})&&e.birthtimeMs===t.birthtimeMs}function sZ(e,t){return Ta(e,t)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.mtimeMs===t.mtimeMs&&e.size===t.size}async function at(e){try{return await Mr.lstat(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function Gi(e){let t=await Mr.lstat(e.file);if(!t.isFile()||t.isSymbolicLink())throw new Error(`${e.label} must be a regular file`);let r=Yq(t),n=await cr({root:Ve(e.paths,e.file),file:e.file,maxBytes:null,label:e.label}),i=await Mr.lstat(e.file);if(!i.isFile()||i.isSymbolicLink()||!sZ(r,Yq(i))||n.hash!==e.expectedHash)throw new Error(`${e.label} content changed or object identity changed while binding`);return{identity:ow(i),size:n.size}}function cZ(e,t,r,n){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`Archive CAS ${t.id} ${r} record must be an object`);let i=e;if(Object.keys(i).sort().join(",")!=="hash,identity,operationId,role,schema")throw new Error(`Archive CAS ${t.id} ${r} record has an invalid shape`);let a=i.identity;if(!a||typeof a!="object"||Array.isArray(a))throw new Error(`Archive CAS ${t.id} ${r} identity must be an object`);let s=a;if(Object.keys(s).sort().join(",")!=="birthtimeMs,dev,ino")throw new Error(`Archive CAS ${t.id} ${r} identity has an invalid shape`);for(let c of["dev","ino","birthtimeMs"])if(typeof s[c]!="number"||!Number.isFinite(s[c])||s[c]<0)throw new Error(`Archive CAS ${t.id} ${r} identity ${c} is invalid`);if(i.schema!==Yf||i.operationId!==t.id||i.role!==r||i.hash!==n)throw new Error(`Archive CAS ${t.id} ${r} record is not transaction-bound`);return{schema:Yf,operationId:t.id,role:r,hash:n,identity:{dev:s.dev,ino:s.ino,birthtimeMs:s.birthtimeMs}}}async function yi(e,t,r,n){let i=await ko(e,t.id),o=gt.join(i.backups,".cas"),a=`.${gt.basename(n)}.comet-archive-cas-${t.id}-${r.id}`,s={directory:o,originalRecord:gt.join(o,`${r.id}.original.json`),postRecord:gt.join(o,`${r.id}.post.json`),candidate:gt.join(gt.dirname(n),".comet-archive-staging",t.id,`${r.id}.candidate`),originalQuarantine:gt.join(gt.dirname(n),`${a}.original`),rollbackQuarantine:gt.join(gt.dirname(n),`${a}.rollback`)};return await Promise.all(Object.values(s).map(c=>ft(Ve(e,c),c))),s}async function zn(e){if(!await at(e.file))return null;let t=await cr({root:e.paths.runtimeDir,file:e.file,maxBytes:null,label:`Archive CAS ${e.operation.id} ${e.role} record`});return cZ(JSON.parse(t.bytes.toString("utf8")),e.operation,e.role,e.expectedHash)}async function aw(e){let t=await zn(e);if(t){if(!Ta(t.identity,e.identity))throw new Error(`Archive CAS ${e.operation.id} ${e.role} object identity changed`);return t}await Li({root:e.paths.runtimeDir,directory:gt.dirname(e.file),label:`Archive CAS ${e.operation.id} records`});let r={schema:Yf,operationId:e.operation.id,role:e.role,hash:e.expectedHash,identity:e.identity};try{await Bt(e.file,r,{containedRoot:e.paths.runtimeDir,exclusive:!0})}catch(i){if(i.code!=="EEXIST")throw i}let n=await zn(e);if(!n||!Ta(n.identity,e.identity))throw new Error(`Archive CAS ${e.operation.id} ${e.role} record changed`);return n}async function Ht(e){let t=await Gi({paths:e.paths,file:e.file,expectedHash:e.record.hash,label:e.label});if(!Ta(e.record.identity,t.identity))throw new Error(`${e.label} object identity changed`)}async function lZ(e){let t=await Gi({paths:e.paths,file:e.file,expectedHash:e.expectedHash,label:e.label}),r=await aw({paths:e.paths,file:e.recordFile,operation:e.operation,role:e.role,expectedHash:e.expectedHash,identity:t.identity});return await Ht({paths:e.paths,file:e.file,operation:e.operation,record:r,label:e.label}),r}async function uZ(e){if(!await at(e.quarantine)||await at(e.target))return;let t=await pl({root:Ve(e.paths,e.target),directory:gt.dirname(e.target),label:`Archive CAS ${e.operation.id} quarantine restoration`});await t.verify();try{await Mr.link(e.quarantine,e.target)}catch(i){if(i.code==="EEXIST")return;throw i}await t.verify();let[r,n]=await Promise.all([Mr.lstat(e.quarantine),Mr.lstat(e.target)]);if(!Ta(ow(r),ow(n)))throw new Error(`Archive CAS ${e.operation.id} could not restore quarantined content`);await Mr.unlink(e.quarantine),await t.verify()}async function tL(e){if(await at(e.quarantine)){await Ht({paths:e.paths,file:e.quarantine,operation:e.operation,record:e.record,label:`Archive ${e.phase} quarantine ${e.operation.target}`});return}let t=await pl({root:Ve(e.paths,e.target),directory:gt.dirname(e.target),label:`Archive ${e.phase} target ${e.operation.target}`});await Ht({paths:e.paths,file:e.target,operation:e.operation,record:e.record,label:`Archive ${e.phase} target ${e.operation.target}`}),await e.hooks?.afterArchiveTargetBound?.(e.phase,e.operation,e.target),await t.verify(),await Ht({paths:e.paths,file:e.target,operation:e.operation,record:e.record,label:`Archive ${e.phase} target ${e.operation.target}`});try{await Mr.rename(e.target,e.quarantine),await t.verify(),await Ht({paths:e.paths,file:e.quarantine,operation:e.operation,record:e.record,label:`Archive ${e.phase} quarantine ${e.operation.target}`})}catch(r){throw await uZ(e),new Error(`Archive ${e.phase} target ${e.operation.target} changed during quarantine`,{cause:r})}await e.hooks?.afterArchiveTargetQuarantined?.(e.phase,e.operation,e.quarantine)}async function Zs(e){if(!await at(e.file))return;await Ht(e);let t=await pl({root:Ve(e.paths,e.file),directory:gt.dirname(e.file),label:e.label});await t.verify(),await Ht(e),await Mr.unlink(e.file),await t.verify()}async function Xq(e,t,r){if(!t.backup||t.expectedTargetHash===null)return;let n=await tr(e,t.target),i=await tr(e,t.backup),o=await wi(i);if(o!==null){if(!Pa(o,t.expectedTargetHash))throw new Error(`Archive transaction backup content changed: ${t.backup}`);return}await dn({target:n,expectedHash:t.expectedTargetHash,label:`Archive transaction target ${t.target}`}),await Cs({sourceRoot:Ve(e,n),source:n,targetRoot:Ve(e,i),target:i,maxBytes:null,label:`Archive transaction backup ${t.backup}`,expectedHash:t.expectedTargetHash,expectedTargetHash:null,exclusive:!0,hooks:{afterParentChainCaptured:()=>r?.afterProtectedCopySourceParentCaptured?.("backup",t.target)}}),await dn({target:i,expectedHash:t.expectedTargetHash,label:`Archive transaction backup ${t.backup}`})}async function rL(e){let t=e.operation.expectedTargetHash;if(t===null)throw new Error(`Archive operation ${e.operation.id} has no original target to quarantine`);let r=await yi(e.paths,e.journal,e.operation,e.target),n=await zn({paths:e.paths,file:r.originalRecord,operation:e.operation,role:"original",expectedHash:t});if(await at(r.originalQuarantine)){if(!n)throw new Error(`Archive apply quarantine ${e.operation.target} has no bound object identity`);return await Ht({paths:e.paths,file:r.originalQuarantine,operation:e.operation,record:n,label:`Archive apply quarantine ${e.operation.target}`}),await Xq(e.paths,e.operation,e.hooks),{record:n,quarantine:r.originalQuarantine}}if(!await at(e.target))throw new Error(`Archive apply target ${e.operation.target} disappeared before quarantine`);return n??=await lZ({paths:e.paths,file:e.target,recordFile:r.originalRecord,operation:e.operation,role:"original",expectedHash:t,label:`Archive apply target ${e.operation.target}`}),await Ht({paths:e.paths,file:e.target,operation:e.operation,record:n,label:`Archive apply target ${e.operation.target}`}),await Xq(e.paths,e.operation,e.hooks),await tL({paths:e.paths,operation:e.operation,phase:"apply",target:e.target,quarantine:r.originalQuarantine,record:n,hooks:e.hooks}),{record:n,quarantine:r.originalQuarantine}}async function Zq(e){let t=await yi(e.paths,e.journal,e.operation,e.target);return await at(t.candidate)?(await Gi({paths:e.paths,file:t.candidate,expectedHash:e.operation.stagedHash,label:`Archive write candidate ${e.operation.target}`}),t.candidate):(await Li({root:Ve(e.paths,t.candidate),directory:gt.dirname(t.candidate),label:`Archive CAS ${e.operation.id} same-volume candidate`}),await Cs({sourceRoot:Ve(e.paths,e.staged),source:e.staged,targetRoot:Ve(e.paths,t.candidate),target:t.candidate,maxBytes:null,label:`Archive transaction staged file ${e.operation.staged}`,expectedHash:e.operation.stagedHash,expectedTargetHash:null,exclusive:!0,hooks:{afterParentChainCaptured:()=>e.hooks?.afterProtectedCopySourceParentCaptured?.("apply",e.operation.staged)}}),t.candidate)}async function dZ(e){let t=e.operation.stagedHash,r=await yi(e.paths,e.journal,e.operation,e.target),n=await zn({paths:e.paths,file:r.postRecord,operation:e.operation,role:"post",expectedHash:t});if(n&&await at(e.target))return await Ht({paths:e.paths,file:e.target,operation:e.operation,record:n,label:`Archive write target ${e.operation.target}`}),await at(r.candidate)&&await Zs({paths:e.paths,file:r.candidate,operation:e.operation,record:n,label:`Archive write candidate ${e.operation.target}`}),n;if(await at(e.target)){let c=await Zq(e),l=await Gi({paths:e.paths,file:c,expectedHash:t,label:`Archive write candidate ${e.operation.target}`}),u=await Gi({paths:e.paths,file:e.target,expectedHash:t,label:`Archive write target ${e.operation.target}`});if(!Ta(l.identity,u.identity))throw new Error(`Archive write target ${e.operation.target} is occupied by an external object`);return n=await aw({paths:e.paths,file:r.postRecord,operation:e.operation,role:"post",expectedHash:t,identity:u.identity}),await Zs({paths:e.paths,file:c,operation:e.operation,record:n,label:`Archive write candidate ${e.operation.target}`}),n}let i=await Zq(e),o=await Gi({paths:e.paths,file:i,expectedHash:t,label:`Archive write candidate ${e.operation.target}`});await Li({root:Ve(e.paths,e.target),directory:gt.dirname(e.target),label:`Archive write target ${e.operation.target}`});let a=await pl({root:Ve(e.paths,e.target),directory:gt.dirname(e.target),label:`Archive write target ${e.operation.target}`});await e.hooks?.beforeArchiveTargetInstall?.("apply",e.operation,e.target),await a.verify(),await Ht({paths:e.paths,file:i,operation:e.operation,record:{schema:Yf,operationId:e.operation.id,role:"post",hash:t,identity:o.identity},label:`Archive write candidate ${e.operation.target}`});try{await Mr.link(i,e.target)}catch(c){throw c.code==="EEXIST"?new Error(`Archive write target ${e.operation.target} was created before exclusive install`,{cause:c}):c}await a.verify(),await e.hooks?.afterArchiveTargetInstalled?.("apply",e.operation,e.target);let s=await Gi({paths:e.paths,file:e.target,expectedHash:t,label:`Archive write target ${e.operation.target}`});if(!Ta(o.identity,s.identity))throw new Error(`Archive write target ${e.operation.target} changed during install`);return n=await aw({paths:e.paths,file:r.postRecord,operation:e.operation,role:"post",expectedHash:t,identity:s.identity}),await Zs({paths:e.paths,file:i,operation:e.operation,record:n,label:`Archive write candidate ${e.operation.target}`}),n}async function fZ(e,t,r,n){let i=await tr(e,r.target),o=await tr(e,r.staged);if(await dn({target:o,expectedHash:r.stagedHash,label:`Archive transaction staged file ${r.staged}`}),r.expectedTargetHash!==null){let a=await yi(e,t,r,i);(!await zn({paths:e,file:a.postRecord,operation:r,role:"post",expectedHash:r.stagedHash})||!await at(i))&&await rL({paths:e,journal:t,operation:r,target:i,hooks:n})}else{let a=await wi(i);if(a!==null&&!Pa(a,r.stagedHash))throw new Error(`Archive transaction target ${r.target} changed before create: ${Ml(a)}`)}await dZ({paths:e,journal:t,operation:r,staged:o,target:i,hooks:n}),await dn({target:i,expectedHash:r.stagedHash,label:`Archive transaction target ${r.target}`})}async function pZ(e,t,r,n){let i=await tr(e,r.target);await rL({paths:e,journal:t,operation:r,target:i,hooks:n}),await dn({target:i,expectedHash:null,label:`Archive transaction target ${r.target}`})}async function mZ(e,t){let r=await tr(e,t.source),n=await tr(e,t.target),[i,o]=await Promise.all([wi(r),wi(n)]);if(!(i===null&&Pa(o,t.expectedSourceHash,"directory"))){if(!Pa(i,t.expectedSourceHash,"directory")||o!==null)throw new Error(`Archive transaction move ${t.id} content changed: source=${Ml(i)}, target=${Ml(o)}`);await Mr.mkdir(gt.dirname(n),{recursive:!0});try{await ro(r,n)}catch(a){throw["EPERM","EACCES","EBUSY"].includes(a.code??"")?new Error(`Native Archive 无法移动 ${r} -> ${n}:外部进程可能仍持有目录句柄。请暂停相关 Agent、编辑器或 CodeGraph 文件监听,释放占用后通过原 Archive 恢复入口继续;原事务和内容已保留。`,{cause:a}):a}await dn({target:n,expectedHash:t.expectedSourceHash,expectedKind:"directory",label:`Archive transaction move target ${t.target}`})}}async function hZ(e,t,r,n){return r.type==="write"?fZ(e,t,r,n):r.type==="remove"?pZ(e,t,r,n):mZ(e,r)}function gZ(e){let t=0,r=!1,n=[];for(let i of e.events){if(i.type!=="operation-started"&&i.type!=="operation-completed")continue;let o=e.journal.operations[t];if(!o||i.operationId!==o.id)throw new Error(`Native Archive transaction ${e.journal.id} operation events are out of order`);if(i.type==="operation-started"){r=!0;continue}if(!r)throw new Error(`Native Archive transaction ${e.journal.id} completed an operation before it started`);n.push(o.id),t+=1,r=!1}return n}async function vZ(e,t,r,n){let i=await tr(e,r.target);if(r.type==="write"){let o=await tr(e,r.staged);await dn({target:o,expectedHash:r.stagedHash,label:`Completed Archive staged file ${r.staged}`});let a=await yi(e,t,r,i),s=await zn({paths:e,file:a.postRecord,operation:r,role:"post",expectedHash:r.stagedHash});if(!s)throw new Error(`Completed Archive target ${r.target} has no CAS identity`);if(await Ht({paths:e,file:i,operation:r,record:s,label:`Completed Archive target ${r.target}`}),r.expectedTargetHash!==null){await dn({target:await tr(e,r.backup),expectedHash:r.expectedTargetHash,label:`Completed Archive backup ${r.backup}`});let c=await zn({paths:e,file:a.originalRecord,operation:r,role:"original",expectedHash:r.expectedTargetHash});if(!c)throw new Error(`Completed Archive target ${r.target} has no original CAS identity`);if(await at(a.originalQuarantine))await Ht({paths:e,file:a.originalQuarantine,operation:r,record:c,label:`Completed Archive original quarantine ${r.target}`});else if(!n)throw new Error(`Completed Archive original quarantine ${r.target} disappeared`)}return}if(r.type==="remove"){await dn({target:i,expectedHash:null,label:`Completed Archive target ${r.target}`}),await dn({target:await tr(e,r.backup),expectedHash:r.expectedTargetHash,label:`Completed Archive backup ${r.backup}`});let o=await yi(e,t,r,i),a=await zn({paths:e,file:o.originalRecord,operation:r,role:"original",expectedHash:r.expectedTargetHash});if(!a)throw new Error(`Completed Archive remove ${r.target} has no original CAS identity`);if(await at(o.originalQuarantine))await Ht({paths:e,file:o.originalQuarantine,operation:r,record:a,label:`Completed Archive original quarantine ${r.target}`});else if(!n)throw new Error(`Completed Archive original quarantine ${r.target} disappeared`);return}n||(await dn({target:await tr(e,r.source),expectedHash:null,label:`Completed Archive move source ${r.source}`}),await dn({target:i,expectedHash:r.expectedSourceHash,expectedKind:"directory",label:`Completed Archive move target ${r.target}`}))}async function nL(e,t,r){let n=t.status==="prepared"?await iw(e,t,"applying"):t;if(n.status!=="applying")throw new Error(`Native Archive transaction ${n.id} cannot apply from ${n.status}`);let i=await xs(e,n.id),o=gZ({journal:n,events:i}),a=new Set(o),s=i.some(l=>l.type==="archive-finalization-started");for(let l of n.operations.slice(0,o.length))await vZ(e,n,l,s);let c=a.size;for(let l of n.operations)a.has(l.id)||(l.id==="archive-change"&&await r?.beforeArchiveChangeMove?.(l),await Fn(e,n.id,"operation-started",l.id),await hZ(e,n,l,r),await Fn(e,n.id,"operation-completed",l.id),c+=1,await r?.afterOperation?.(l,c));return n=await CE(e,n.id),n}async function wZ(e){try{return await Ht(e),!0}catch{return!1}}async function yZ(e){await Ht({paths:e.paths,file:e.quarantine,operation:e.operation,record:e.record,label:`Archive rollback original quarantine ${e.operation.target}`});let t=await pl({root:Ve(e.paths,e.target),directory:gt.dirname(e.target),label:`Archive rollback target ${e.operation.target}`});await e.hooks?.beforeArchiveTargetInstall?.("rollback",e.operation,e.target),await t.verify(),await Ht({paths:e.paths,file:e.quarantine,operation:e.operation,record:e.record,label:`Archive rollback original quarantine ${e.operation.target}`});try{await Mr.link(e.quarantine,e.target)}catch(r){throw r.code==="EEXIST"?new Error(`Archive rollback target ${e.operation.target} was created before exclusive restore`,{cause:r}):r}await t.verify(),await e.hooks?.afterArchiveTargetInstalled?.("rollback",e.operation,e.target),await Ht({paths:e.paths,file:e.target,operation:e.operation,record:e.record,label:`Archive rollback target ${e.operation.target}`})}async function EE(e){if(e.operation.type!=="write")return;let t=await yi(e.paths,e.journal,e.operation,e.target);if(!await at(t.candidate))return;let r=await Gi({paths:e.paths,file:t.candidate,expectedHash:e.operation.stagedHash,label:`Archive write candidate ${e.operation.target}`});await Zs({paths:e.paths,file:t.candidate,operation:e.operation,record:{schema:Yf,operationId:e.operation.id,role:"post",hash:e.operation.stagedHash,identity:r.identity},label:`Archive write candidate ${e.operation.target}`})}async function kZ(e,t,r,n){let i=await tr(e,r.target),o=await yi(e,t,r,i),a=r.expectedTargetHash,s=a===null?null:await zn({paths:e,file:o.originalRecord,operation:r,role:"original",expectedHash:a}),c=r.type==="write"?await zn({paths:e,file:o.postRecord,operation:r,role:"post",expectedHash:r.stagedHash}):null;if(r.type==="write"&&!c&&await at(o.candidate)&&await at(i)){let l=await Gi({paths:e,file:o.candidate,expectedHash:r.stagedHash,label:`Archive write candidate ${r.target}`}),u=await Gi({paths:e,file:i,expectedHash:r.stagedHash,label:`Archive rollback target ${r.target}`});Ta(l.identity,u.identity)&&(c=await aw({paths:e,file:o.postRecord,operation:r,role:"post",expectedHash:r.stagedHash,identity:u.identity}))}if(await at(o.rollbackQuarantine)){if(!c)throw new Error(`Archive rollback quarantine ${r.target} has no CAS identity`);await Ht({paths:e,file:o.rollbackQuarantine,operation:r,record:c,label:`Archive rollback quarantine ${r.target}`})}if(await at(i)&&!(s!==null&&await wZ({paths:e,file:i,operation:r,record:s,label:`Archive rollback target ${r.target}`}))){if(!c){if(!s){let u=await wi(i);if(Pa(u,a)){await EE({paths:e,journal:t,operation:r,target:i});return}}throw new Error(`Archive rollback target ${r.target} is occupied by an external object`)}await tL({paths:e,operation:r,phase:"rollback",target:i,quarantine:o.rollbackQuarantine,record:c,hooks:n})}if(a===null){if(await at(i))throw new Error(`Archive rollback create target ${r.target} could not be removed`)}else if(!await at(i)){if(!s||!await at(o.originalQuarantine))throw new Error(`Archive rollback original target ${r.target} cannot be recovered safely`);await yZ({paths:e,operation:r,target:i,quarantine:o.originalQuarantine,record:s,hooks:n})}s&&await at(o.originalQuarantine)&&await Zs({paths:e,file:o.originalQuarantine,operation:r,record:s,label:`Archive rollback original quarantine ${r.target}`}),c&&await at(o.rollbackQuarantine)&&await Zs({paths:e,file:o.rollbackQuarantine,operation:r,record:c,label:`Archive rollback quarantine ${r.target}`}),await EE({paths:e,journal:t,operation:r,target:i}),await dn({target:i,expectedHash:a,label:`Archive rollback target ${r.target}`})}async function bZ(e,t){let r=await tr(e,t.source),n=await tr(e,t.target),[i,o]=await Promise.all([wi(r),wi(n)]);if(!(Pa(i,t.expectedSourceHash,"directory")&&o===null)){if(i!==null||!Pa(o,t.expectedSourceHash,"directory"))throw new Error(`Archive rollback move ${t.id} content changed: source=${Ml(i)}, target=${Ml(o)}`);await Mr.mkdir(gt.dirname(r),{recursive:!0}),await Mr.rename(n,r)}}async function iL(e,t){for(let r of t.operations){if(r.type!=="write")continue;let n=await tr(e,r.target),i=await yi(e,t,r,n);for(let o of[gt.dirname(i.candidate),gt.dirname(gt.dirname(i.candidate))]){await ft(Ve(e,o),o);try{await Mr.rmdir(o)}catch(a){if(!["ENOENT","ENOTEMPTY","EEXIST"].includes(a.code??""))throw a}}}}async function oL(e,t,r){let n=await xs(e,t.id);if(n.some(a=>a.type==="archive-finalization-started"||a.type==="archive-finalized"))throw new Error("An archive whose finalization started can only be recovered by continuing it");let i=await iw(e,t,"rolling-back");await Fn(e,i.id,"rollback-started");let o=new Set(n.filter(a=>a.type==="operation-started"||a.type==="operation-completed").map(a=>a.operationId));for(let a of[...i.operations].reverse())o.has(a.id)&&(a.type==="move"?await bZ(e,a):await kZ(e,i,a,r));return await iL(e,i),await Fn(e,i.id,"rollback-completed"),i=await iw(e,i,"rolled-back"),i}async function eL(e,t,r){let n=await tr(e,r.target);if(r.type==="write"){let i=await yi(e,t,r,n),o=await zn({paths:e,file:i.postRecord,operation:r,role:"post",expectedHash:r.stagedHash});if(!o)throw new Error(`Archive commit target ${r.target} has no CAS identity`);await Ht({paths:e,file:n,operation:r,record:o,label:`Archive commit target ${r.target}`});return}await dn({target:n,expectedHash:null,label:`Archive commit target ${r.target}`})}async function AZ(e,t){for(let r of t.operations){if(r.type==="move")continue;let n=await tr(e,r.target),i=await yi(e,t,r,n);if(await at(i.rollbackQuarantine))throw new Error(`Archive commit found an unfinished rollback for ${r.target}`);if(await eL(e,t,r),r.expectedTargetHash!==null){let o=await zn({paths:e,file:i.originalRecord,operation:r,role:"original",expectedHash:r.expectedTargetHash});if(!o)throw new Error(`Archive commit target ${r.target} has no original CAS identity`);await at(i.originalQuarantine)&&await Zs({paths:e,file:i.originalQuarantine,operation:r,record:o,label:`Archive commit original quarantine ${r.target}`})}await EE({paths:e,journal:t,operation:r,target:n})}for(let r of t.operations)r.type!=="move"&&await eL(e,t,r)}async function sw(e,t,r){return r==="commit"&&(await AZ(e,t),await iL(e,t)),await Fn(e,t.id,r),r==="commit"?iw(e,t,"committed"):t}Hi();Ra();St();He();dv();vl();function aL(e,t){let r=t.operations.find(n=>n.id==="archive-change");if(!r||r.type!=="move")throw new Error(`Archive transaction ${t.id} has no archive move`);return Fl.resolve(e.nativeRoot,...r.target.split("/"))}async function sL(e,t,r){let n=await xs(e,t.id);if(n.some(g=>g.type==="archive-finalized"))return;let i=n.some(g=>g.type==="archive-finalization-started");if(t.schema==="comet.native.transaction.v2"&&!i){let g=t.operations.find(w=>w.id==="archive-change");if(!g||g.type!=="move"||!g.expectedSourceHash)throw new Error(`Archive transaction ${t.id} has no content-bound archive move`);let v=await wi(aL(e,t));if(v?.kind!=="directory"||v.hash!==g.expectedSourceHash)throw new Error(`Native Archive content changed before finalization for transaction ${t.id}`)}let o=aL(e,t),a=Fl.join(o,Vn),s=await hB(a);if(!t.change||s.name!==t.change)throw new Error(`Archive transaction ${t.id} change mismatch`);let c=hn(e,s.name),l=await Sl(c);if(!l||l.runId!==s.run_id||l.currentStep!=="archive"&&!(l.currentStep===null&&l.status==="completed"))throw new Error(`Native archive Run state is missing or inconsistent for ${s.name}`);let u=l;if(l.currentStep==="archive"){let g=Qq(Ia,l,new Set,uE,void 0);if(!g.action)throw new Error(g.reason??"Native archive produced no action");u=Uq(Ia,g.state,{actionId:g.action.id,status:"succeeded",summary:`Archived Native change ${s.name}`},uE,void 0)}let f=Rr(`archive:${t.id}:${s.name}`),d=await Ws(c,u.trajectoryRef),p=d.filter(g=>g.data.transactionId===t.id);if(t.schema==="comet.native.transaction.v2"&&(p.length>1||p.some(g=>g.type!=="state_transitioned")))throw new Error(`Native Archive trajectory has a transaction id collision: ${t.id}`);let m=p.find(g=>g.type==="state_transitioned"),h={previousPhase:"archive",nextPhase:null,evidenceHash:f,summary:`Archived Native change ${s.name}`,transactionId:t.id};if(m&&t.schema==="comet.native.transaction.v2"&&(!RZ(m.data,h)||m.runId!==u.runId||m.timestamp!==t.createdAt||m!==d.at(-1)))throw new Error(`Native Archive trajectory event changed for transaction ${t.id}`);if(!i&&(s.archived||l.currentStep===null||p.length>0))throw new Error(`Native Archive finalization state changed before its irreversible marker: ${t.id}`);if(i||(t.schema==="comet.native.transaction.v2"?(await sw(e,t,"archive-finalization-started"),await r?.afterFinalizationStarted?.(t)):await gl(e,t,"archive-finalization-started")),!s.archived){let g={...s,archived:!0};await mB(a,g)}m||(m=await Jf({changeDir:c,run:u,type:"state_transitioned",data:h,...t.schema==="comet.native.transaction.v2"?{now:new Date(t.createdAt)}:{}})),await Yv({changeDir:c,run:u,trajectoryOffset:m.sequence,evidenceHash:f,...t.schema==="comet.native.transaction.v2"?{now:new Date(t.createdAt)}:{}}),await Hg(c,u),await oS(e,s.name),t.schema==="comet.native.transaction.v2"?await sw(e,t,"archive-finalized"):await gl(e,t,"archive-finalized")}async function NZ(e,t,r){if(t.schema==="comet.native.transaction.v2"){let o=await nL(e,t,{...r,beforeArchiveChangeMove:async s=>{await r?.beforeArchiveChangeMove?.(s);let c=await Aa(e,t.change);if(c.phase!=="archive"||c.archived||c.verification_result!=="pass")throw new Error("Legacy Archive state changed; preserve the original transaction and approved materials")}});return await sL(e,o,r),await sw(e,o,"commit")}let n=await t$(e,t);return await sL(e,n,r),await gl(e,n,"commit")}function SZ(e,t){if(t.kind!=="archive")throw new Error(`Transaction ${t.id} is not an archive`);if(t.schema==="comet.native.transaction.v2"){if(!t.change)throw new Error(`Archive transaction ${t.id} has no change`);return}if(Fl.resolve(t.projectRoot)!==Fl.resolve(e.projectRoot)||Fl.resolve(t.nativeRoot)!==Fl.resolve(e.nativeRoot))throw new Error(`Transaction ${t.id} belongs to a different Native root`)}async function cL(e){return $e(e.paths,async()=>{let t=await Hn(e.paths,e.transactionId),r=t.schema==="comet.native.transaction.v2"?await CE(e.paths,e.transactionId):t;return SZ(e.paths,r),r.status==="committed"||r.status==="rolled-back"?r:e.strategy==="continue"?await NZ(e.paths,r):r.schema==="comet.native.transaction.v2"?oL(e.paths,r):kg(e.paths,r)},{allowedTransactionId:e.transactionId})}vl();Es();import{promises as EL}from"node:fs";import{accessSync as CZ,constants as _Z,promises as Hl}from"node:fs";import At from"node:path";dt();var uL=dr(Ur(),1);Sr();sg();Er();Se();import{promises as EZ}from"node:fs";import lL from"node:path";var cw=class extends Error{};async function _E(e,t){let r=await Pe({root:e.nativeRoot,ref:lL.relative(e.nativeRoot,t).replaceAll("\\","/"),maxBytes:null,includeHash:!1}),n=(0,uL.parse)(r.text);if(["comet.native.v1","comet.native.v2","comet.native.v3"].includes(n?.schema))throw new cw("Historical Native schema");return{projectRoot:e.projectRoot,file:t,state:M(n)}}async function dL(e,t,r){let n;try{n=await EZ.readdir(e.archiveDir,{withFileTypes:!0})}catch(o){if(o.code==="ENOENT")return[];throw o}if(n.length>4096)throw new Error("Native archive discovery exceeds 4096 records");let i=[];for(let o of n){if(!o.isDirectory()||o.isSymbolicLink())continue;let a=/^\d{4}-\d{2}-\d{2}-(.+)$/u.exec(o.name)?.[1];if(r!==void 0&&a!==void 0&&a!==r)continue;let s=lL.join(e.archiveDir,o.name,"comet-state.yaml");try{let c=await _E(e,s);c.state.archived&&c.state.status==="done"&&i.push(c)}catch(c){if(c.code==="ENOENT"||c instanceof cw)continue;let l=o.name.replace(/^\d{4}-\d{2}-\d{2}-/u,"");t?.(l,`Native archive ${o.name} is unreadable: ${c.message}`)}}return i}Nu();Sr();it();tv();Hi();dv();el();Pf();Nu();var fL="comet.native.workspace-finish.v1",hL="[a-z][a-z0-9]*(?:-[a-z0-9]+)*",gL=new RegExp(`^${hL}$`,"u"),IZ=/^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/u,ec=/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u;function pL(e,t){if(!e.trim()||e.includes("\0"))throw new Error(`${t} must contain non-whitespace text and no NUL character`)}function xZ(e){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Native workspace finish journal is invalid");let t=e;if(t.schema!==fL||typeof t.name!="string"||!gL.test(t.name)||typeof t.transactionId!="string"||!IZ.test(t.transactionId)||t.archiveDir!==null&&(typeof t.archiveDir!="string"||!At.isAbsolute(t.archiveDir))||!["pending","blocked"].includes(String(t.status))||typeof t.updatedAt!="string"||!Number.isFinite(Date.parse(t.updatedAt)))throw new Error("Native workspace finish journal is invalid");if(t.result!==null){if(!t.result||typeof t.result!="object"||Array.isArray(t.result))throw new Error("Native workspace finish journal result is invalid");let r=t.result;if(!["merge","push","pull-request","keep"].includes(String(r.action))||!["completed","kept","blocked"].includes(String(r.status))||!Array.isArray(r.blockedPaths)||r.blockedPaths.some(n=>typeof n!="string")||r.recoveryArgs!==null&&(!Array.isArray(r.recoveryArgs)||r.recoveryArgs.some(n=>typeof n!="string")))throw new Error("Native workspace finish journal result is invalid")}if(t.plan!==void 0){let r=t.plan;if(!r||typeof r!="object"||!["keep","merge","push","pull-request"].includes(r.finish)||!["current","branch","worktree"].includes(r.isolation)||![r.changeRoot,r.primaryRoot].every(n=>typeof n=="string"&&At.isAbsolute(n))||![r.changeBranch,r.targetBranch].every(n=>typeof n=="string"&&n.length>0)||r.targetRoot!==null&&(typeof r.targetRoot!="string"||!At.isAbsolute(r.targetRoot))||r.remote!==null&&typeof r.remote!="string"||typeof r.commitMessage!="string"||r.mergeMessage!==null&&typeof r.mergeMessage!="string")throw new Error("Native workspace finish journal plan is invalid");pL(r.commitMessage,"commit-message"),r.mergeMessage!==null&&pL(r.mergeMessage,"merge-message")}if(t.createdAt!==void 0&&(typeof t.createdAt!="string"||!Number.isFinite(Date.parse(t.createdAt))))throw new Error("Native workspace finish journal creation identity is invalid");if(t.commit!==void 0){let r=t.commit;if(!r||!ec.test(r.parent)||!Array.isArray(r.paths)||!r.paths.every(n=>typeof n=="string"&&n.length>0&&!At.posix.isAbsolute(n)&&!At.win32.isAbsolute(n)&&!n.split("/").includes(".."))||!Array.isArray(r.entries)||!r.entries.every(n=>typeof n=="string")||r.sha!==null&&!ec.test(r.sha))throw new Error("Native workspace finish journal commit is invalid")}if(t.merge!==void 0){let r=t.merge;if(!r||!ec.test(r.target)||!ec.test(r.source)||r.sha!==null&&!ec.test(r.sha))throw new Error("Native workspace finish journal merge is invalid")}return{schema:fL,name:t.name,transactionId:t.transactionId,archiveDir:t.archiveDir,status:t.status,result:t.result,updatedAt:t.updatedAt,...t.createdAt===void 0?{}:{createdAt:t.createdAt},...t.plan===void 0?{}:{plan:t.plan},...t.commit===void 0?{}:{commit:t.commit},...t.merge===void 0?{}:{merge:t.merge}}}function vL(e,t){if(!gL.test(t))throw new Error(`Invalid Native workspace finish journal name: ${t}`);return At.join(e.transactionsDir,`workspace-finish-${t}.json`)}async function PZ(e,t,r={}){let n=vL(e,t);try{let i=await Hl.lstat(n);if(!i.isFile()||i.isSymbolicLink())throw new Error("Native workspace finish journal is not a regular file");let o=xZ(JSON.parse(await Hl.readFile(n,"utf8")));if(o.name!==t)throw new Error("Native workspace finish journal name is invalid");return o}catch(i){if(i.code==="ENOENT")return null;if(r.onError)return r.onError(t,i instanceof Error?i.message:String(i)),null;throw i}}async function wL(e,t={}){let r;try{r=await Hl.readdir(e.transactionsDir,{withFileTypes:!0})}catch(i){if(i.code==="ENOENT")return[];throw i}let n=[];for(let i of r){if(!i.isFile()&&!i.isSymbolicLink()||i.isDirectory())continue;let o=new RegExp(`^workspace-finish-(${hL})\\.json$`,"u").exec(i.name);if(!o)continue;let a=await PZ(e,o[1],t);a&&n.push(a)}return n}async function yL(e,t){try{await Hl.unlink(vL(e,t))}catch(r){if(r.code!=="ENOENT")throw r}}async function TZ(e,t){if(!t.archiveDir||!bL(e.archiveDir,t.archiveDir)||At.resolve(e.archiveDir)===At.resolve(t.archiveDir))throw new Error("Native workspace finish journal has no safe archived change directory");let r=await _E(e,At.join(t.archiveDir,"comet-state.yaml"));if(r.state.name!==t.name||!r.state.archived||r.state.status!=="done"||t.createdAt!==void 0&&r.state.created_at!==t.createdAt)throw new Error("Native workspace finish journal does not match a completed Archive record");return r}function OZ(e,t,r){return te(e,r?["ls-tree","-r","-z",r,"--",...t]:["ls-files","--stage","-z","--",...t]).split("\0").filter(Boolean).map(i=>{let o=r?/^(\d+) (?:blob|commit) ([a-f0-9]+)\t([\s\S]+)$/u.exec(i):/^(\d+) ([a-f0-9]+) 0\t([\s\S]+)$/u.exec(i);if(!o)throw new Error("Native workspace finish encountered an unresolved index entry");return`${o[1]} ${o[2]} ${o[3]}`}).sort()}function jZ(e,t,r){try{return te(e,["merge-base","--is-ancestor",t.parent,r]),t.sha&&te(e,["merge-base","--is-ancestor",t.sha,r]),JSON.stringify(OZ(e,t.paths,r))===JSON.stringify(t.entries)}catch{return!1}}async function $Z(e,t,r,n,i){let o=[];async function a(s){for(let c of await Hl.readdir(s,{withFileTypes:!0})){if(c.isSymbolicLink())throw new Error("Native archived record contains a symbolic link");let l=At.join(s,c.name);c.isDirectory()?await a(l):c.isFile()&&o.push(l)}}await a(r);for(let s of t.spec_changes){let c=ev(e,s.capability);await FZ(c)&&o.push(c)}try{if(te(n,["ls-tree","-r","--name-only",i,"--",ki(e.projectRoot,Fi(e,t.name))]))return!1;let s=l=>{let u=ki(e.projectRoot,l);return te(n,["rev-parse",`${i}:${u}`])===te(n,["hash-object","--path",u,"--",l])};if(At.resolve(n)!==At.resolve(e.projectRoot))return o.every(s);let c=o.map(l=>ki(e.projectRoot,l));for(let l=0;l<c.length;){let u=l,f=0;for(;u<c.length&&u-l<32;){let p=Buffer.byteLength(JSON.stringify(c[u]),"utf8")+1;if(u>l&&f+p>8192)break;f+=p,u++}let d=c.slice(l,u);try{let p=te(n,["--literal-pathspecs","ls-tree","-r","-z",i,"--",...d]).split("\0").filter(Boolean),m=new Map;for(let g of p){let v=/^\d+ blob ([a-f0-9]+)\t([\s\S]+)$/u.exec(g);if(!v||!ec.test(v[1]))return!1;m.set(v[2],v[1])}let h=te(n,["hash-object","--",...d]).split(/\r?\n/u);if(h.length!==d.length||h.some((g,v)=>!ec.test(g)||g!==m.get(d[v])))return!1}catch{if(!o.slice(l,u).every(s))return!1}l=u}return!0}catch{return!1}}async function kL(e,t){let r=await TZ(e,t),n=t.plan??await MZ({paths:e,state:r.state,archiveDir:t.archiveDir});if(!n)return!0;if(At.resolve(n.changeRoot)!==At.resolve(e.projectRoot)||n.isolation!==r.state.workspace.isolation||n.isolation!=="current"&&(n.changeBranch!==r.state.workspace.change_branch||n.targetBranch!==r.state.workspace.target_branch||n.finish!==r.state.workspace.finish)||ue(n.changeRoot).currentBranch!==n.changeBranch&&(n.isolation!=="branch"||n.finish!=="merge"||ue(n.changeRoot).currentBranch!==n.targetBranch))return!1;let i=te(n.changeRoot,["rev-parse",`refs/heads/${n.changeBranch}`]),o=RL(e,r.state,t.archiveDir);if(pc(n.changeRoot).some(a=>AL(a,o)))return!1;if(t.commit){let a=[ki(e.projectRoot,Fi(e,t.name)),ki(e.projectRoot,t.archiveDir),...r.state.spec_changes.map(s=>ki(e.projectRoot,ev(e,s.capability))),ki(e.projectRoot,iS(e))];if(JSON.stringify(t.commit.paths)!==JSON.stringify(a)||!jZ(n.changeRoot,t.commit,i))return!1}if(!await $Z(e,r.state,t.archiveDir,n.changeRoot,i))return!1;if(n.finish==="keep")return!0;if(n.finish==="merge")try{return te(n.changeRoot,["merge-base","--is-ancestor",i,`refs/heads/${n.targetBranch}`]),!0}catch{return!1}return!1}var lw=class extends Error{constructor(r,n,i="Native workspace finish is blocked"){super(`${i}; remaining paths: ${r.join(", ")}`);this.paths=r;this.workspaceRoot=n;this.name="NativeWorkspaceFinishPreparationError"}paths;workspaceRoot};function bL(e,t){let r=At.relative(e,t);return r===""||!At.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${At.sep}`)}function ki(e,t){let r=At.relative(e,t).replaceAll("\\","/");if(!r||r===".."||r.startsWith("../")||At.isAbsolute(r))throw new Error(`Native workspace finish path escaped the project: ${t}`);return r}function AL(e,t){return t.some(r=>e===r||e.startsWith(`${r}/`))}function RL(e,t,r,n=[]){let i=[...Md(e.projectRoot)?[".comet/config.yaml"]:[],ki(e.projectRoot,Fi(e,t.name)),ki(e.projectRoot,iS(e))];r&&i.push(ki(e.projectRoot,r));for(let o of r?t.spec_changes:n)i.push(ki(e.projectRoot,ev(e,o.capability)));return i}function DZ(e,t){let r=pc(e).filter(n=>!AL(n,t));if(r.length>0)throw new lw(r,e)}function BZ(e,t){return t.map(r=>At.resolve(e,...r.split("/")))}function WZ(e){let t=pc(e).filter(r=>!(r===".comet/config.yaml"&&Md(e)));if(t.length>0)throw new lw(BZ(e,t),e,`Native merge target worktree is not clean: ${e}`)}function mL(e){try{if(te(e,["config","--get","user.name"])&&te(e,["config","--get","user.email"]))return}catch{}throw new Error("Native workspace finish requires configured Git user.name and user.email")}function qZ(e,t){for(let r of Yt(e))if(ue(r).currentBranch===t)return r;return null}function LZ(e,t){try{Xp(e,t,{timeoutMs:1e4})}catch(r){throw new Error(`${e} is required for the selected Native workspace finish`,{cause:r})}}function VZ(e,t){if(!t)return;let r=t.command[0];try{if(At.posix.isAbsolute(r)||At.win32.isAbsolute(r))throw new Error("configured executable must not be an absolute path");if(/[\\/]/u.test(r)){let i=At.resolve(e,r);if(!bL(e,i))throw new Error("configured executable escapes the project root");CZ(i,_Z.X_OK);return}Xp(process.platform==="win32"?"where":"which",[r],{timeoutMs:1e4})}catch(n){throw new Error(`Configured Native pull request finish executable is not available: ${r}`,{cause:n})}}async function MZ(e){let{paths:t,state:r}=e,n=r.workspace,i=ue(t.projectRoot);if(n.isolation==="current"){if(!i.isGitWorktree)return null;if(!i.primaryWorktreeRoot||!i.currentBranch)throw new Error("Native current workspace finish requires a registered Git branch");return mL(t.projectRoot),{finish:"keep",changeRoot:t.projectRoot,primaryRoot:i.primaryWorktreeRoot,changeBranch:i.currentBranch,targetBranch:i.currentBranch,targetRoot:t.projectRoot,remote:null,isolation:"current",pullRequestFinish:null}}if(!n.finish||!n.change_branch||!n.target_branch)throw new Error("Native isolated workspace finish is not persisted");if(n.change_branch===n.target_branch)throw new Error("Native change and target branches must be different for workspace finish");if(!i.primaryWorktreeRoot||i.currentBranch!==n.change_branch)throw new Error(`Native workspace finish requires branch ${n.change_branch} in the current registered worktree`);mL(t.projectRoot);let o=RL(t,r,e.archiveDir,e.appliedSpecChanges);n.finish!=="keep"&&DZ(t.projectRoot,o);let a=n.isolation==="branch"?t.projectRoot:qZ(i.primaryWorktreeRoot,n.target_branch);if(n.finish==="merge"&&n.isolation==="worktree"){if(!a)throw new Error(`Native merge finish requires a registered worktree on target branch ${n.target_branch}`);WZ(a)}let s=n.finish==="push"||n.finish==="pull-request"?CI(t.projectRoot,n.change_branch):null;return n.finish==="pull-request"&&(LZ("gh",["--version"]),VZ(t.projectRoot,e.pullRequestFinish)),{finish:n.finish,changeRoot:t.projectRoot,primaryRoot:i.primaryWorktreeRoot,changeBranch:n.change_branch,targetBranch:n.target_branch,targetRoot:a,remote:s,isolation:n.isolation,pullRequestFinish:e.pullRequestFinish??null}}async function FZ(e){try{return await Hl.access(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}Hi();zg();ze();or();import NL from"node:path";async function SL(e,t){let r=await EL.readdir(e.transactionsDir,{withFileTypes:!0}).catch(i=>{if(i.code==="ENOENT")return[];throw i}),n=[];for(let i of r){let o=dl(i.name);if(!(!i.isDirectory()&&!o))try{if(i.isSymbolicLink())throw new Error("事务路径不能是符号链接");let a=o?await cf(e,i.name):null,s=a?.journal??await Hn(e,i.name);if(t&&s.change!==t||(a?!fg(a):["committed","rolled-back"].includes(s.status)))continue;let c=o?.kind==="archive"&&await Fe(e.projectRoot,"native",o.change,{readOnly:!0});n.push({id:s.id,change:s.change,kind:a?.kind??("kind"in s?s.kind:"transaction"),status:s.status,recoveryCommandArgs:o?["comet","native",o.kind==="archive"?"archive":"doctor",o.change,...o.kind==="archive"?[c?"--recover":"--confirmed"]:["--repair"]]:["comet","native","doctor","--transaction",s.id,"--repair","--strategy","<continue|rollback>"]})}catch(a){n.push({id:i.name,kind:o?.kind??"transaction",status:"invalid",message:a instanceof Error?a.message:String(a)})}}return n}async function CL(e,t){let r=Na(e,"--repair"),n=Na(e,"--migrate-history"),i=_l(e,"--stopped-actions"),o=_l(e,"--strategy"),a=_l(e,"--transaction");Na(e,"--confirmed");let s=e[0]?.startsWith("--")?void 0:e.shift();if(kB(e),n&&(r||i||o||a))throw new sn("--migrate-history cannot combine with other mutation flags");if(o!==void 0&&!["continue","rollback"].includes(o))throw new sn("--strategy must be continue or rollback");if(o&&!r)throw new sn("--strategy requires --repair");let c=await RB(t);if(a){if(!r||!o)throw new sn("--transaction requires --repair --strategy <continue|rollback>");let E=await cL({paths:c,transactionId:a,strategy:o});return Qi("doctor",{transaction:E})}let l=!1;if(r&&o&&(await Vq({projectRoot:t,strategy:o}),l=!0),n){let E=s?[s]:await k$(t,"native"),I=[],W=[],F=[];for(let G of E)try{let Z;try{Z=await Gs(t,G)}catch(Ae){if(!(Ae instanceof Error)||!Ae.message.startsWith("Conflicting active and history Runtime owners for "))throw Ae;await _g(t,"native",G),Z=await Gs(t,G)}["completed","cancelled"].includes(Z.run.status)?await zs({projectRoot:t,run:Z.run,recover:!0})?I.push(G):F.push({change:G,code:"native-history-closure-pending",message:"Native history closure remains pending; inspect the original Run and complete its business cleanup."}):W.push(G)}catch(Z){F.push({change:G,code:"native-history-migration-failed",message:Z instanceof Error?Z.message:String(Z)})}return{...Qi("doctor",{healthy:F.length===0,migrated:I,active:W,...F.length?{findings:F}:{}}),exitCode:F.length?65:0}}let u=(await Te(t))?.native.pending_root_move,f=await SL(c,s);if(r){for(let E of f)E.kind!=="migration"||E.status==="invalid"||!E.change||(await bE({paths:c,name:E.change}),l=!0);l&&(f=await SL(c,s))}let d=(await wL(c)).filter(E=>!s||E.name===s),p=[];for(let E of d){let I=E.archiveDir?await kL(c,E):!1;r&&I?(await yL(c,E.name),l=!0):p.push({change:E.name,status:E.status,completed:I,archiveDir:E.archiveDir,recoveryCommandArgs:["comet","native","archive",E.name,"--confirmed"]})}let m={transactions:f,workspaceFinishes:p};if(!s){let E=await EL.readdir(c.changesDir,{withFileTypes:!0}).catch(F=>{if(F.code==="ENOENT")return[];throw F}),I=[];for(let F of E)if(!(!F.isDirectory()||F.isSymbolicLink()))try{if(await Ps(c,F.name)){let Z=await wn(c,F.name);I.push({name:F.name,schema:Z.schema,status:"current",phase:Z.phase});continue}let G=await Tf(c,F.name);I.push({name:F.name,schema:G.schema,status:G.status,phase:G.state?.phase,...G.schema==="comet.native.v4"?{}:{recoveryCommandArgs:["comet","native","doctor",F.name,"--repair"]}})}catch(G){I.push({name:F.name,schema:null,status:"invalid",message:G instanceof Error?G.message:String(G)})}let W=[];for(let F of await A$(t))try{await Gs(t,F,{readOnly:!0})}catch(G){W.push({change:F,code:"native-history-invalid",message:G instanceof Error?G.message:String(G)})}return{...Qi("doctor",{...m,changes:I,healthy:I.every(F=>F.schema==="comet.native.v4"&&F.status==="current")&&!f.length&&!p.length&&!u&&!W.length,...W.length?{findings:W}:{},repaired:l,pendingRootMove:u??null,...u?{recoveryCommand:"comet native doctor --repair --strategy <continue|rollback> --json"}:{}}),exitCode:W.length?65:0}}let h=await Fe(t,"native",s),g=()=>Qi("doctor",{healthy:!1,repaired:!1,runtimeFormat:"sdk",change:s,recovery:{code:"runtime-recovery-required",reason:"Original SDK Run needs checkpoint recovery; preserve its portable approval and claims.",commandArgs:["comet","native","doctor",s,"--repair","--confirmed"]}});if(!h&&!r)try{if(await _a(Pt(c,s)))return g()}catch(E){if(E.code!=="ENOENT")throw E}if(!h&&(f.length||d.length))return Qi("doctor",{...m,change:s,healthy:!f.length&&!p.length,repaired:l});if(!h&&r&&(await oE(c,s),h=await Fe(t,"native",s),h&&(l=!0)),h){let E=h.application==="native"&&!await ht({singleWriter:!0,rootDir:NL.join(Le(t),"sdk-runs/native")}).read(h.runId);if(E&&!r)return g();let I=await Gs(t,s,{readOnly:!r});E&&(l=!0),r&&(I.run.status==="cancelled"?await Uv({projectRoot:t,run:I.run}):I.run.status==="completed"&&await Jv({projectRoot:t,run:I.run}));let W=await fq({projectRoot:t,name:s},I);return{...Qi("doctor",{...W,...m,healthy:W.diagnostics.healthy&&!f.length&&!p.length,repaired:l,...i?{notice:"旧进程停止回执不再用于推进;请在 Agent 平台核对原任务和实际副作用。"}:{}}),exitCode:0}}if(!await Ps(c,s)){let E;try{let W=await Tf(c,s);if(!W.state)throw new Error(W.message??`Native change ${s} is unreadable`);E=W.state}catch(W){if(W.code!=="ENOENT")throw W;let F=(await dL(c,void 0,s)).filter(G=>G.state.name===s);if(!F.length)throw W;if(F.length!==1)throw new Error("同名 Native 归档不唯一,请核对原归档路径;诊断不会选择或迁移其中一个。",{cause:W});return await _a(F[0].file)?g():Qi("doctor",{healthy:!0,repaired:l,runtimeFormat:"compat",change:s,state:Ll(F[0].state,c)})}let I=[];if(E.run_id||await kE(c,s)){let W=await Ug(c,s);r&&W.status==="repairable"?await eB(c,s):W.status!=="clean"&&I.push({code:"trajectory-invalid",severity:"error",path:W.file,message:W.status==="invalid"?W.message:`Native Run trajectory has a repairable ${W.reason} tail; run doctor --repair`})}if(!r||I.length)return Qi("doctor",{healthy:!1,repaired:!1,runtimeFormat:"compat",state:E,findings:I,recoveryCommandArgs:["comet","native","doctor",s,"--repair"],instruction:"旧业务文档需要显式导入;只读诊断不写入材料或启动执行。"});await bE({paths:c,name:s}),l=!0}let v=await wn(c,s),w=[],y=await Dr(c,s,{diagnostics:!0}),R=v.children_contract;if(!R)try{R=(await pn({changeDir:NL.join(c.changesDir,s),policy:"advisory",validation:fn(v),...v.acceptance.length?{acceptanceIds:v.acceptance.map(E=>E.id)}:{}}))?.contract}catch(E){w.push({code:"portable-supervisor-contract-unavailable",message:"restore children.yaml and retry next: "+E.message})}y&&!R&&!w.length&&w.push({code:"portable-supervisor-contract-unavailable",message:"restore children.yaml and retry next; confirmed Child scope is missing"});let N=y?.children.filter(E=>E.status==="ready"&&E.dependsOn.some(I=>!y.children.some(W=>W.name===I&&["integrated","archived"].includes(W.status)))).map(E=>E.name)??[];if(N.length&&y&&R&&(r?(y=Vh({state:y,contract:R}),await mo(c,y),l=!0):w.push({code:"portable-supervisor-ready-dependencies-unmet",message:"Confirmed Child dependencies are not integrated; run doctor "+s+" --repair"})),R&&v.workspace.change_branch===null)try{await Hh(c,s);let E=Ng(v.workspace,t);w.push({code:"portable-supervisor-git-binding-missing",message:E?"Confirm Shape to bind the Supervisor to "+E.change_branch:"Initialize Git and confirm the Supervisor Shape on a clean branch"})}catch(E){w.push({code:"portable-supervisor-git-binding-missing",message:E.message})}let b=y||R?.schema==="comet.native.children.v1"?await Ag({paths:c,state:v}):null;return{...Qi("doctor",{healthy:w.length===0,repaired:l,...w.length?{findings:w}:{},...r&&N.length?{supervisorDependencyRepair:N}:{},runtimeFormat:"compat",state:Ll(v,c),continuation:ql(v,b),instruction:"旧业务进度和批准继续保留;普通检查与任务由 Agent 平台执行,Comet 不恢复旧进程。"}),exitCode:w.length?65:0}}import{Buffer as _L}from"node:buffer";var HZ=new Set(["continuation","input","commandArgs","userCommunication","current","pendingAction","changedPaths","artifactRefs","artifacts"]);function QZ(e){if("outputView"in e)return e;let t={},r=new Map,n=new WeakMap,i=u=>u.replace(/~/gu,"~0").replace(/\//gu,"~1"),o=(u,f)=>/requests?$/iu.test(u)||f!==null&&typeof f=="object"&&"operation"in f,a=u=>{if(u===null||typeof u!="object")return!1;let f=n.get(u);if(f!==void 0)return f;let d=Object.entries(u).some(([p,m])=>o(p,m)||a(m));return n.set(u,d),d},s=(u,f,d,p)=>{if(o(d,u)||/(?:hash|revision|attempt|claim|token|blockers|workspace)$/iu.test(d))return u;if(p&&(typeof u=="string"&&u.length>=160||HZ.has(d)&&u!==null&&typeof u=="object"&&!a(u))){let h=JSON.stringify(u);if(h.length>=160){let g=r.get(h);if(g!==void 0&&g.length+f.length+8<h.length){t[f]=g;return}return r.set(h,f),u}}return Array.isArray(u)?u.map((h,g)=>s(h,`${f}/${g}`,"",!1)):u!==null&&typeof u=="object"?Object.fromEntries(Object.entries(u).flatMap(([h,g])=>{let v=s(g,`${f}/${i(h)}`,h,!0);return v===void 0?[]:[[h,v]]})):u},c={..."data"in e?{data:e.data}:{},...e};return{...s(c,"","",!1),outputView:{schema:"comet.cli.compact.v1",mode:"compact",references:t,instruction:"references maps omitted JSON Pointers to equal values in this response (RFC 6901). Resolve references recursively to restore the full JSON. Request templates remain complete. Omit --compact for the full envelope."}}}function IL(e,t){if(!t||!e)return e;let r=JSON.parse(e);if(r===null||typeof r!="object"||Array.isArray(r))return e;let n=QZ(r),i=n.outputView;if(!i?.references||Object.keys(i.references).length===0)return e;let o=`${JSON.stringify(n)}
|
|
472
|
+
`;return _L.byteLength(o)<_L.byteLength(e)?o:e}Sr();import uw from"node:path";function Yi(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:{}}async function xL(e,t){if(e.error?.code==="usage"||e.command==="hook-guard")return e;let r=Yi(e.data),n=Yi(r.continuation);if(Yi(r.builderReadiness).ready===!1&&n.action==="builder-handoff")return e;let i=typeof r.change=="string"?r.change:typeof r.name=="string"?r.name:t.name,o=i&&/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(i)?i:void 0,a=e.executionCwd??uw.resolve(t.projectRoot);o&&e.exitCode!==0&&!e.executionCwd&&(a=await XW(a,o,{readOnly:!0}).catch(()=>a));let s=w=>zv(w,a),c=s(["comet","native","doctor",...o?[o]:[]]),l=Yi(r.state),u=Yi(r.workspaceFinishResult),f=typeof u.message=="string"?u.message:e.error?.message??"",d=f.toLowerCase(),p=d.split(`
|
|
473
|
+
`),m=p.some(w=>{let y=w.indexOf("worktree");return y!==-1&&w.indexOf("locked",y+8+1)!==-1}),h=d.includes("index.lock")||d.includes("cannot lock ref")||m||p.some(w=>{let y=w.indexOf("unable to create");return y!==-1&&w.indexOf(".lock",y+16+1)!==-1}),g={schema:"comet.native.recovery.v1",code:"runtime-recovery-required",reason:e.error?.message??(typeof Yi(r.recovery).reason=="string"?Yi(r.recovery).reason:"Inspect the original execution and its retained evidence."),affectedPaths:[],owner:null,diagnosticArgs:c,recoveryArgs:null,preconditions:["Inspect the original Action before retrying; preserve its receipts."],preserved:{candidateId:Yi(l.builder_handoff).candidate_id??r.candidateId??null,shapeConfirmationHash:l.shape_confirmation_hash??r.shapeConfirmationHash??null}},v=Yi(r.recovery).schema?r.recovery:Yi(n.recovery).schema?n.recovery:void 0;if(h){let w=typeof u.targetRoot=="string"?u.targetRoot:a,y=[];try{/index\.lock/iu.test(f)?y.push(uw.resolve(w,te(w,["rev-parse","--git-path","index.lock"]))):m&&y.push(uw.join(uw.resolve(w,te(w,["rev-parse","--git-dir"])),"locked"))}catch{}v={...g,code:"git-lock",reason:f,affectedPaths:y,owner:null,diagnosticArgs:["git","-C",w,"status","--short"],recoveryArgs:Array.isArray(u.recoveryArgs)?s(u.recoveryArgs):Array.isArray(n.commandArgs)?s(n.commandArgs):e.command==="archive"&&o?s(["comet","native","archive",o]):null,preconditions:["Inspect the original Git command result and resolve its reported Git condition before retrying.","Resolve the reported Git lock or worktree condition, then retry the retained workflow step."]}}else if(!v&&(e.exitCode!==0||n.disposition==="blocked")){let w=Array.isArray(u.recoveryArgs)?u.recoveryArgs:n.commandArgs;v={...g,code:u.status==="blocked"?"workspace-conflict":e.command==="archive"?"archive-blocked":"runtime-recovery-required",reason:typeof u.message=="string"?u.message:g.reason,affectedPaths:Array.isArray(u.blockedPaths)?u.blockedPaths:[],diagnosticArgs:Array.isArray(u.diagnosticArgs)?u.diagnosticArgs:c,recoveryArgs:Array.isArray(w)&&w.every(y=>typeof y=="string")?s(w):null,preconditions:["Resolve the reported file, transaction, or execution conflict, then retry the original step."]}}return v?{...e,data:{...r,recovery:v,...n.schema?{continuation:{...n,recovery:v}}:{}},...e.error?{envelope:{summary:v.reason,next:{command:(v.recoveryArgs??v.diagnosticArgs).map(w=>/^[\w./:=+@-]+$/u.test(w)?w:JSON.stringify(w)).join(" ")}}}:{}}:e}it();async function PL(e,t,r=process.argv.slice(2)){let n=r.indexOf("--"),i=n<0?[...r]:r.slice(0,n),o=n<0?[]:r.slice(n),a=i.includes("--json"),s=i.includes("--verbose"),c=i.includes("--compact"),l,u,f,d;try{if(Na(i,"--json"),Na(i,"--compact"),c&&!a)throw new sn("--compact requires --json");Na(i,"--verbose"),l=_l(i,"--project-root");let m=[...i,...o];u=m[0]?.startsWith("--")?void 0:m[0];let h=async()=>{let g=await bB(l);return{executionCwd:g,...await t(m,g)}};d=AB(e,m)?await Zp(h):await h()}catch(m){f=m,d=SB(e,m)}d=await xL(d,{projectRoot:d.executionCwd??l??process.cwd(),name:u,error:f});let p=EB(d,a,s);return p.stdout&&process.stdout.write(IL(p.stdout,c&&a)),p.stderr&&process.stderr.write(p.stderr+(p.stderr.endsWith(`
|
|
474
|
+
`)?"":`
|
|
475
|
+
`)),p.exitCode}process.exitCode=await PL("doctor",CL);
|